R foreach根本没有循环

时间:2014-10-22 16:03:15

标签: r domc parallel-foreach

我在使用Linux x64上的包foreach尝试合并doMC语句的输出时遇到了一些麻烦:

# I'm running 33 different models, one for each label
library(doMC)
registerDoMC(2)

labels = paste0('y', 1:33)
dataset = get.Data()
test.data = get.Test()

pred = foreach(yi = labels, .combine = cbind) %dopar% {

    # handle special case, don't need a model here
    if (yi == 'y14')
        y.pred = 0
    else {
        # fit model
        fit  = glm(y ~ ., data = data.frame(y = dataset[, yi], dataset[, -1]))
        # get predicted probabilities
        y.pred = predict(fit, test.data, type = 'response')
    }
    y.pred
}

# This gives me an error, saying pred is not a matrix
colnames(pred) = labels

`Error in `colnames<-`(`*tmp*`, value = c("y1", "y2", "y3", "y4", "y5",  : 
attempt to set 'colnames' on an object with less than two dimensions`

实际上,pred是具有第一个预测的向量,因此其他标签根本不运行。这很奇怪,因为这很好用:

library(doMC)
registerDoMC(2)
set.seed(1)
M = foreach(i = 1:4, .combine = cbind) %dopar% {runif(3)}
print(M)

      result.1  result.2   result.3   result.4
[1,] 0.1370338 0.1556492 0.12846072 0.24629143
[2,] 0.3940809 0.4537018 0.69545139 0.02654378
[3,] 0.6287515 0.2379316 0.02993252 0.17504858

PS。:doSNOW()给出了同样的错误! 谢谢你的任何澄清!

0 个答案:

没有答案