对于简单的引导示例,我有以下代码。
X <- runif(100)
errors <- rexp(length(X))-1
Y <- 1 + 2*X + errors
ols.mod <- lm(Y ~ X)
boot <- Boot(ols.mod, method = "case", R = 1000)
如果以单独的行执行,则上面的代码有效。但是,当我将代码包装在如下函数中时:
test_func <- function() {
X <- runif(100)
errors <- rexp(length(X))-1
Y <- 1 + 2*X + errors
ols.mod <- lm(Y ~ X)
boot <- Boot(ols.mod, method = "case", R = 1000)
}
test_func()
执行此操作将产生如下错误:
Error in eval(predvars, data, env): object 'Y' not found
关于为什么发生这种情况的任何想法?谢谢!
答案 0 :(得分:0)
这对我有用。
doBootstrapping <- function(n = 100, r = 1000) {
xy <- data.frame(X = runif(n = n))
errors <- rexp(length(xy$X))-1
xy$Y <- 1 + 2*xy$X + errors
ols.mod <- lm(Y ~ X, data = xy)
boot <- Boot(ols.mod, method = "case", R = r)
}
out <- doBootstrapping(n = 100, r = 1000)
> str(out)
List of 11
$ t0 : Named num [1:2] 0.986 1.953
..- attr(*, "names")= chr [1:2] "(Intercept)" "X"
$ t : num [1:1000, 1:2] 1.188 1.073 1.083 1.127 0.964 ...
..- attr(*, "dimnames")=List of 2
.. ..$ : NULL
.. ..$ : chr [1:2] "(Intercept)" "X"
$ R : num 1000
$ data :'data.frame': 100 obs. of 1 variable:
..$ .zero: int [1:100] 0 0 0 0 0 0 0 0 0 0 ...
$ seed : int [1:626] 403 334 599478801 441938554 -1355732193 -409499586 -248637084 -2048103023 20568410 1088692573 ...
$ statistic:function (data, indices, .fn)
$ sim : chr "ordinary"
$ call : language boot::boot(data = dd, statistic = boot.f, R = R, .fn = f, parallel = parallel_env, ncpus = ncores)
$ stype : chr "i"
$ strata : num [1:100] 1 1 1 1 1 1 1 1 1 1 ...
$ weights : num [1:100] 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 ...
- attr(*, "class")= chr "boot"
- attr(*, "boot_type")= chr "boot"