External loop variable in n foreach loop

I am trying to use the foreach package in a nested loop, but my inner loop does not recognize the external counter, what am I missing?

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) } } 
+6
source share
1 answer

The problem is that you are using the %:% operator incorrectly. It is designed to combine two foreach objects, resulting in a single foreach object that can be used to repeatedly evaluate any expression that you provide to it. So, if you want to use %:% , you need to first combine the two foreach() , and then use the resulting object to control one call to %do% (or in your case %dopar% ). Below is an example (1) below.

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

In any case, although for parallel jobs, I prefer to use %:% . Your code, however, like (3) below, combines the elements of two strategies to create a hybrid that can do nothing.

 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 
+16
source

Source: https://habr.com/ru/post/910539/


All Articles