I've read that the correct way to do nested foreach loops in R is via the nesting operator %:%
(e.g. https://cran.r-project.org/web/packages/foreach/vignettes/nested.html).
However, code can't be added between the inner and outer loops when using this approach -- see example below.
Is there a way to create nested, parallelised foreach loops such that code can be added between the inner and outer loops?
More generally, is there anything wrong with the obvious way that springs to mind, namely simply nesting two foreach loops with the %dopar%
operator instead of the %:%
operator? See trivial example below.
library(foreach)
# Set up backend
cl = makeCluster(6)
registerDoParallel(cl)
on.exit(stopCluster(cl))
# Run nested loop with '%:%' operator. Breaks if adding code between the inner and outer loops
foreach(i=1:2) %:%
# a = 1 #trivial example of running code between outer and inner loop -- throws error
foreach(j = 1:3) %dopar% {
i * j
}
# Run nested loop using 2 '%dopar%' statements -- is there anything wrong with this?
foreach(i=1:2, .packages = 'foreach') %dopar% {
a = 1 #trivial example of running code between outer and inner loop
foreach(j = 1:3) %dopar% {
i * j
}
}