首页 文章

使用doParallel时的范围问题

提问于
浏览
3

我正在尝试使用 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 是多余的 .

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

1 回答

  • 3

    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()) 构造 .

相关问题