[英]Functions Causing Objects to Disappear
我遇到过这种非常奇怪的情况。 基本上,我正在尝试将累积分布函数拟合到数据的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
局部ModelFit
,但似乎也似乎是函数的某些区域的局部变量。
任何帮助将不胜感激。
您在其中做很多隐式的事情……我建议您更明确地编写事情。
具体来说, mydata.Gest$r <- new_r
然后在绘图公式plot(..., cbind(rs, theo) ~ r, ...)
中用r
替换new_r
。 这对我行得通。 不确定为什么它不能在函数外部而不是内部运行,而是依靠plot
在mydata.Gest
的本地范围之外查找mydata.Gest
的new_r
是有风险的。
同样,使用=
将内容分配给数据帧中的列,而不是<-
从干净的会话中:
data.frame(x<-1:10, y<- 1:10)
ls()
与
data.frame(x=1:10, y=1:10)
ls()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.