这是我遇到的一个非常奇怪的情况。基本上,我试图将累积分布函数与我的数据的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
是局部的,但它似乎对函数中的某些区域也是局部的。
如有任何帮助,我们将不胜感激。
你在那里做了很多隐含的事情。。。我建议写得更明确一些。
具体地说,mydata.Gest$r <- new_r
在您的绘图公式plot(..., cbind(rs, theo) ~ r, ...)
中将new_r
替换为r
。这对我来说很有效。不知道为什么它在函数之外而不是在函数内部工作,但依赖plot
在mydata.Gest
的本地范围之外查找new_r
是有风险的。
此外,使用=
将内容分配给数据帧中的列,而不是<-
来自干净会话:
data.frame(x<-1:10, y<- 1:10)
ls()
与
data.frame(x=1:10, y=1:10)
ls()