且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-10-14 18:45:51

The problem is that you are incorrectly applying the %:% operator. It is designed to merge two foreach objects, resulting in a single foreach object that can be used to repeatedly evaluate whatever expression you supply to it. So, if you want to use %:%, you need to first merge the two foreach() statements, and then use the resulting object to drive a single call to %do% (or in your case, %dopar%). See (1) below for an example.

Alternatively, if you want to nest the two foreach() objects, use %do% twice, as in (2) below.

Either way works, although for parallel jobs I might prefer the one using %:%. Your code, though, like (3) below, combines elements of the two strategies to produce a hybrid that can't do anything.

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