嵌套R foreach循环中的外循环变量

时间:2012-03-12 20:42:34

标签: r foreach

我正在尝试在嵌套循环中使用foreach包,但是我的内部循环不识别外部计数器,我错过了什么?

v3 <- search.compounds.by.mass(100.05,0.5)
foreach(j=2:length(v2)) %:% {
    foreach(i=1:length(v3), .combine=rbind) %dopar% {
        write.table(paste(v3[i], paste(get.reactions.by.compound(v3[i]), collapse=" "), sep=" "), "file1",quote=FALSE, row.names=FALSE, col.names=FALSE, append=TRUE)
        write.table(paste(v3[i], paste(get.pathways.by.compounds(v3[i]), collapse=" "), sep=" "), "file2",quote=FALSE, row.names=FALSE, col.names=FALSE, append=TRUE)
        v3 <- search.compounds.by.mass(v2[j],0.5)
    }
}

1 个答案:

答案 0 :(得分:16)

问题是您错误地应用了%:%运算符。它旨在合并两个foreach对象,从而生成一个foreach对象,可用于重复计算您提供给它的表达式。因此,如果您要使用%:%,则需要首先合并两个foreach()语句,然后使用生成的对象来驱动单次拨打%do%(或在您的情况下,%dopar%)。有关示例,请参阅下面的(1)

或者,如果您要嵌套两个foreach()个对象,请使用%do%两次,如下面的(2)

无论哪种方式都有效,但对于并行作业,我可能更喜欢使用%:%的作业。但是,您的代码,如下面的(3),将两种策略的元素组合在一起,生成一种无法做任何事情的混合。

X <- c("A", "B")
Y <- 1:3

## (1) EITHER merge two 'foreach' objects using '%:%' ...
foreach (j = X, .combine = c) %:% foreach(i = Y, .combine = c) %do% {
    paste(j, i, sep = "")
}
# [1] "A1" "A2" "A3" "B1" "B2" "B3"


## (2) ... OR Nest two 'foreach' objects using a pair of '%do%' operators ...
foreach(j = X, .combine = c) %do% {
    foreach(i = Y, .combine = c) %do% {
        paste(j, i, sep = "")
    }
}
# [1] "A1" "A2" "A3" "B1" "B2" "B3"


## (3) ... BUT DON'T use a hybrid of the approaches.
foreach(j = X, .combine = c) %:% {
    foreach(i = Y, .combine = c) %do% {
        paste(j, i, sep = "")
    }
}
# Error in foreach(j = X, .combine = c) %:% { : 
#   "%:%" was passed an illegal right operand