导致对象消失的功能

时间:2012-08-02 19:29:05

标签: r function variables object spatstat

这是一个非常奇怪的情况,我遇到过。基本上,我正在尝试将累积分布函数拟合到我的数据的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的局部函数,但它似乎也是函数中某些区域的局部函数。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:6)

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

具体而言,mydata.Gest$r <- new_r然后在您的地图公式new_r中将r替换为plot(..., cbind(rs, theo) ~ r, ...)。这对我行得通。不确定为什么它在函数之外而不是在函数内部工作,但是依赖于plot来查看mydata.Gest的{​​{1}}的局部范围之外是有风险的。

另外,使用new_r将内容分配给数据框中的列而不是=

来自干净的会议:

<-

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