好的,这就是我发现的:问题是当对 nlsBoot 的调用在函数内部时。下面的代码应该会复制问题(nlsBoot 找不到变量 d):
library(nlstools)
call_thisFunction <- function(){
X=c(69, 36, 135, 66, 10, 6, 15, 18)
Y=c(0.10008780, 0.20840336, 0.08147234, 0.12500000, 0.19444444, 0.60000000, 0.21978022, 0.29411765)
d<- data.frame(X=X,Y=Y)
print(d)
thisfit<- nls(Y ~ a*X^b,data=d, start = list(a = .1, b = .1))
print("done NLS")
a= nlsBoot(thisfit, niter = 50) #FAIL - Error in eval(expr, envir, enclos) : object 'd' not found
}
call_thisFunction()
我还注意到,如果我将变量 d 设为全局:
d<<- data.frame(X=X,Y=Y)
或者在调用之前在函数之外定义它:
(...)
d=c()
call_thisFunction()
一切正常。如果有人知道原因,请发布。谢谢!
这是一个修复(注释掉的行来自原始行,并被它们后面的行替换):
# nlsBoot <- function(nls, niter = 999)
nlsBoot <- function (nls, niter = 999, envir = parent.frame())
{
if (!inherits(nls, "nls"))
stop("Use only with 'nls' objects")
# data2 <- eval(nls$data, sys.frame(0))
data2 <- eval(nls$data, envir)
fitted1 <- fitted(nls)
resid1 <- resid(nls)
var1 <- all.vars(formula(nls)[[2]])
l1 <- lapply(1:niter, function(i) {
data2[, var1] <- fitted1 + sample(scale(resid1, scale = FALSE),
replace = TRUE)
nls2 <- try(update(nls, start = as.list(coef(nls)), data = data2),
silent = TRUE)
if (inherits(nls2, "nls"))
return(list(coef = coef(nls2), rse = summary(nls2)$sigma))
})
if (sum(sapply(l1, is.null)) > niter/2)
stop(paste("Procedure aborted: the fit only converged in",
round(sum(sapply(l1, is.null))/niter), "% during bootstrapping"))
tabboot <- sapply(l1[!sapply(l1, is.null)], function(z) z$coef)
rseboot <- sapply(l1[!sapply(l1, is.null)], function(z) z$rse)
recapboot <- t(apply(tabboot, 1, quantile, c(0.5, 0.025,
0.975)))
colnames(recapboot) <- c("Median", "2.5%", "97.5%")
estiboot <- t(apply(tabboot, 1, function(z) c(mean(z), sd(z))))
colnames(estiboot) <- c("Estimate", "Std. error")
serr <- sum(sapply(l1, is.null))
if (serr > 0)
warning(paste("The fit did not converge", serr, "times during bootstrapping"))
listboot <- list(coefboot = t(tabboot), rse = rseboot, bootCI = recapboot,
estiboot = estiboot)
class(listboot) <- "nlsBoot"
return(listboot)
}