在foreach中导出变量

时间:2015-10-08 17:31:01

标签: r foreach parallel-foreach doparallel

我在foreach包中将数据框导出到%dopar%时遇到问题。如果我将%do%registerDoSEQ()一起使用,但registerDoParallel()我总是得到:

Error in { : task 1 failed - "object 'kyphosis' not found"

以下是使用kyphosis包中的rpart数据的可重现示例。我想尝试逐步回归逐步回归:

library(doParallel)
library(foreach)
library(rpart)

invars <- c('Age', 'Number', 'Start')
n_vars <- 2
vars <- length(invars)
iter <- trunc(vars/n_vars)
threads <- 4
if (vars%%n_vars == 0) iter <- iter - 1
iter <- 0:iter

cl <- makeCluster(threads)
registerDoParallel(cl)
#registerDoSEQ()

terms <- ''
min_formula <- paste0('Kyphosis~ 1', terms)
fit <- glm(formula = as.formula(min_formula), data = kyphosis, family = 'binomial')

out <- foreach(x = iter, .export = 'kyphosis') %dopar%  {

  nv <- invars[(x * n_vars + 1):(min(x * n_vars + n_vars, vars))]
  sfit <- step(object = fit, trace =FALSE, scope = list(
    lower = min_formula,
    upper = as.formula(paste(min_formula, '+', paste0(nv, collapse = '+')))),
    steps = 1, direction = 'forward')
  aic <- sfit$aic

  names(aic) <- if(nrow(sfit$anova) == 2) sfit$anova$Step[2]
  aic
}
out
stopCluster(cl)

1 个答案:

答案 0 :(得分:0)

在调用foreach函数之前将其添加到step的正文中:

.GlobalEnv$kyphosis <- kyphosis

我不确定为什么会发生这种情况,但我的观点是step使用glm中存储的信息调用fit$call。{/ p>

glm(formula = as.formula(min_formula), family = "binomial", data = kyphosis)

使用新的更新公式,但部分data = kyphosis保持不变。因此glm会尝试在全局环境中查找kyphosis