Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parallel foreach with two arguments

I have this code:

  library(doParallel)
    registerDoParallel(cores = 8)

    result = foreach(A = c(1, 2, 3),B = c(10, 20), .combine = list) %dopar% {
    A*B
}

result

[[1]]
[1] 10

[[2]]
[1] 40

but I want: 10, 20, 30, 20, 40, 60

like image 989
user1436187 Avatar asked Jul 29 '26 20:07

user1436187


1 Answers

The values in A and B are iterators that advance in parallel. This is not a nested loop. In such a foreach construction, after each iteration the next value of the sequence A and the next value of the sequence B is selected, until the end of any one of the sequences is reached. A not particularly elegant workaround consists in substantially increasing the size of the sequences A and B in an ordered way, like this:

library(doParallel)
registerDoParallel(cores = 8)
result <- foreach( A =rep(c(1,2,3),2), B = rep(c(10, 20), each=3), 
                  .combine='cbind') %dopar% { A*B }
#> result
#     result.1 result.2 result.3 result.4 result.5 result.6
#[1,]       10       20       30       20       40       60

There are certainly better ways to solve the problem, but this might be helpful to illustrate why you obtained an unexpected result. In any case I hope this helps.

like image 88
RHertel Avatar answered Aug 01 '26 12:08

RHertel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!