"object not found" 在 foreach 循环中

"object not found" in foreach loop

我正在使用 vars 库在 R 中 运行 创建向量自回归模型,我想将 foreach 函数并行用于 运行 模型,但它会产生一个错误说

Error in { : task 1 failed - "object 'exogen.train' not found"

如果不包含外生变量,代码 运行 没问题,但是一旦我将它们添加到模型中,就会发生错误。以下是错误的最小示例:

library(vars)
library(doParallel)

set.seed(123)
dat <- ts(matrix(rnorm(600), 200, 3), start = c(1961, 1), frequency = 12)
dat.train <- dat[1:100, ]
dat.test <- dat[101:200, ]

label <- sample(1:5, nrow(dat), replace = T)
exogen.train <- cbind(label = label[1:100])
exogen.test <- cbind(label = label[101:200])

ncores <- 6
cl <- makeCluster(ncores)
registerDoParallel(cl)

res <- foreach(i = 1:6, .combine = rbind, .packages = c("vars")) %dopar% {
    fit.VAR <- VAR(dat.train, p = i, type = "none", exogen = exogen.train)
    
    pred.valid <- predict(fit.VAR, dat.test, dumvar = exogen.test, n.ahead = nrow(dat.test))
    res <- lapply(pred.valid$fcst, sd)
    return(list(c(i, res)))
}
stopCluster(cl)
res

即使我将所有内容都移到循环内,错误仍然存​​在。但是如果不包含外生变量,那么代码运行没问题:

ncores <- 6
cl <- makeCluster(ncores)
registerDoParallel(cl)

res <- foreach(i = 1:6, .combine = rbind, .packages = c("vars")) %dopar% {
    fit.VAR <- VAR(dat.train, p = i, type = "none")
    
    pred.valid <- predict(fit.VAR, dat.test, n.ahead = nrow(dat.test))
    res <- lapply(pred.valid$fcst, sd)
    return(list(c(i, res)))
}
stopCluster(cl)
res

使用 R 4.2 可以在 Windows 和 Mac 以及使用 R 3.62 的 Linux 上重现错误。

这显然是 VAR() 函数内部尝试从全局环境再次访问 exogen 的一些问题。查看线程 here

所以您的解决方案是将 .GlobalEnv$exogen.train <- exogen.train 添加到您的循环中:

res <- foreach(i = 1:6, .combine = rbind, .packages = c("vars")) %dopar% {
  .GlobalEnv$exogen.train <- exogen.train
  fit.VAR <- VAR(dat.train, p = i, type = "none", exogen = exogen.train)
  pred.valid <- predict(fit.VAR, dat.test, dumvar = exogen.test, n.ahead = nrow(dat.test))
  res <- lapply(pred.valid$fcst, sd)
  return(list(c(i, res)))
}