这是我遇到的一个非常奇怪的情况。基本上,我试图将累积分布函数拟合到我的数据的 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
,但它似乎也似乎是函数中某些区域的局部。
任何帮助将不胜感激。