我在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)
答案 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
。