使用 doParallel 时的范围问题

Scoping issue when using doParallel

我正在尝试使用 doParallel 包估计多个非参数模型。我的问题似乎与 np 包有关。 看看这个可重现的例子:

library(np)
library(doParallel)

df     <- data.frame(Y = runif(100, 0, 10), X = rnorm(100))
models <- list(as.formula(Y ~ X))

npestimate <- function(m, data) {
  LCLS <- npregbw(m, data = data, regtype = "lc", bwmethod = "cv.ls")
  LLLS <- npregbw(m, data = data, regtype = "ll", bwmethod = "cv.ls")
  # sigt <- npsigtest(LCLS, boot.method = "wild", boot.type = "I")
  return(list(LCLS = LCLS, LLLS = LLLS))
}

cl <- makeCluster(length(models))
registerDoParallel(cl)

results <- foreach(m = models, .packages = "np", .verbose = T) %dopar% 
  npestimate(m, data = df)

stopCluster(cl)

如您所见,我创建了一个名为 npestimate() 的函数,以便为每个模型计算不同的内容。我在要使用 npsigtest 运行 显着性测试的地方注释掉了一行。通常,npsigtest 通过查看调用 npregbw 的环境来获取使用的数据。

但这在这里不起作用。我不确定为什么,但是 npsigtest 就是找不到上面两行代码中使用的数据。 数据自动导出到节点,所以在foreach中使用.export是多余的。

关于如何使这项工作有任何建议吗?

npsigtest 几乎复制了 lm 中使用的方法和 lm 对象的功能。因此,它具有相同的潜在范围界定陷阱。问题是与公式相关的环境:

environment(models[[1]])
#<environment: R_GlobalEnv>

修复起来很容易:

npestimate <- function(m, data) {
  environment(m) <- environment()
  LCLS <- npregbw(m, data = data, regtype = "lc", bwmethod = "cv.ls")
  LLLS <- npregbw(m, data = data, regtype = "ll", bwmethod = "cv.ls")
  sigt <- npsigtest(LCLS, boot.method = "wild", boot.type = "I")
  return(list(LCLS = LCLS, LLLS = LLLS))
}

由于这些问题,我实际上经常更喜欢 eval(bquote()) 结构。