4

这是我遇到的一个非常奇怪的情况。基本上,我试图将累积分布函数拟合到我的数据的 G 函数中。这样做之后,我想绘制模型和原始数据,并将其输出为 PDF。我将允许代码解释(只需复制和粘贴):

library(spatstat)

data(swedishpines)

mydata <- swedishpines

mydata.Gest <- Gest(mydata)

Gvalues <- mydata.Gest$rs

count <- (which(Gvalues == 1))[1]

new_r <- seq(1/count, length(Gvalues)/count, by = 1/count)

GvsR_dataframe <- data.frame(G <- Gvalues, R <- new_r)

themodel <- suppressWarnings(nls(G ~ pnorm(R, mean, sd), data = GvsR_dataframe, start = list(mean=0.4, sd=0.2), trace = FALSE))

pdf(file = "ModelPlot.pdf")

plot(mydata.Gest, cbind(rs, theo) ~ new_r, lty = c(1, 2), col = c("black", "red"), xlim = c(0, max(new_r)), ylim = c(0,1), main = paste("Model-fitting for G Function \n Mean = ",as.numeric(coef(themodel)[1]),"\n Standard Deviation = ",as.numeric(coef(themodel)[2]), sep=''), ylab = "G(r)", xlab = "Distance Between Particles (r)", legend = NULL)
lines(new_r, predict(themodel), lty = 2, col = "blue")
legend("bottomright", c("CSR", "Swedish Pines", "Normal Probability \n Density Function"), lty = c(2, 4, 1, 2), col = c("red", "black", "blue"), bg = 'grey', border = 'black')

graphics.off()

上面的代码完美运行。

现在是奇怪的部分。

当我将所有命令封装mydata <- swedishpines为一个函数并mydata成为该函数的输入时,它不再起作用。下面的代码应该像最后一段代码一样执行,但事实并非如此。

library(spatstat)

data(swedishpines)

mydata <- swedishpines

ModelFit <- function(mydata) {

mydata.Gest <- Gest(mydata)

Gvalues <- mydata.Gest$rs

count <- (which(Gvalues == 1))[1]

new_r <- seq(1/count, length(Gvalues)/count, by = 1/count)

GvsR_dataframe <- data.frame(G <- Gvalues, R <- new_r)

themodel <- suppressWarnings(nls(G ~ pnorm(R, mean, sd), data = GvsR_dataframe, start = list(mean=0.4, sd=0.2), trace = FALSE))

pdf(file = "ModelPlot.pdf")

plot(mydata.Gest, cbind(rs, theo) ~ new_r, lty = c(1, 2), col = c("black", "red"), xlim = c(0, max(new_r)), ylim = c(0,1), main = paste("Model-fitting for G Function \n Mean = ",as.numeric(coef(themodel)[1]),"\n Standard Deviation = ",as.numeric(coef(themodel)[2]), sep=''), ylab = "G(r)", xlab = "Distance Between Particles (r)", legend = NULL)
lines(new_r, predict(themodel), lty = 2, col = "blue")
legend("bottomright", c("CSR", "Swedish Pines", "Normal Probability \n Density Function"), lty = c(2, 4, 1, 2), col = c("red", "black", "blue"), bg = 'grey', border = 'black')

graphics.off()

}

ModelFit(mydata)

出现以下错误:

Error in eval(expr, envir, enclos) : object 'new_r' not found

我很困惑。我已经为此工作了很长时间,只是无法想出解决这个问题的方法。PDF 已输出,但已损坏,无法打开。我不知道为什么new_r“消失”,但这样做会导致所有绘图操作停止。显然new_r是函数的局部ModelFit,但它似乎也似乎是函数中某些区域的局部。

任何帮助将不胜感激。

4

1 回答 1

6

你在那里做了很多隐含的东西......我建议更明确地写东西。

具体来说,mydata.Gest$r <- new_r然后在您的绘图公式中替换new_r为. 这对我行得通。不知道为什么它在函数外部而不是内部起作用,但是依赖于在 for的本地范围之外寻找是有风险的。 rplot(..., cbind(rs, theo) ~ r, ...)plotmydata.Gestnew_r

此外,用于=将事物分配给数据框中的列,而不是<-

从干净的会话中:

data.frame(x<-1:10, y<- 1:10)
ls()

相对

data.frame(x=1:10, y=1:10)
ls()
于 2012-08-02T19:47:25.827 回答