1

I have noticed a different behaviour using %do% and %dopar% concerning the management of the variables. Here is a MWE to show what I mean

library(foreach)
library(doParallel)
library(iterators)

a = 1
foreach(icount(10)) %do% {a = a + 1}
print(a)
# [1] 11

registerDoParallel(cores = 1)
a = 1
foreach(icount(10)) %dopar% {a = a + 1}
print(a)
# [1] 1

In the first case a is incremented while in the second one the loop takes a copy and a does not change. I was expected the second behaviour with %dopar% to apply also with %do%. Is there a way to enforce that without using %dopar% (because I'm using nested foreachloops as in the foreach vignette).

svick
  • 236,525
  • 50
  • 385
  • 514
ClementWalter
  • 4,814
  • 1
  • 32
  • 54
  • it's an iterator (see iterators package or foreach vignette). It's the same as `foreach(i=c(1:10))` – ClementWalter Jan 20 '16 at 10:23
  • you get `2` as a result of the calculation into the loop. But the variable `a` does not change – ClementWalter Jan 20 '16 at 10:28
  • 1
    Maybe the the answer to [this question](http://stackoverflow.com/questions/18763376/global-assignment-parallelism-and-foreach) could help – NicE Jan 20 '16 at 10:42
  • 1
    And maybe another [related](http://stackoverflow.com/questions/34653567/doparallel-foreach-inconsistently-inherits-objects-from-parent-environment-e#comment57059883_34653567) – Tensibai Jan 20 '16 at 10:44
  • Why do you need this? Usually you should use the return value of the `foreach` loop. – Roland Jan 20 '16 at 10:59
  • You can wrap your code in `local`. – Roland Jan 20 '16 at 11:02
  • @Roland indeed my problem is like having an `apply` into a `for` loop for some varying criteria. From the foreach vignette I got a way to create a parallel `apply` using two nested `foreach` loops. – ClementWalter Jan 20 '16 at 14:49

0 Answers0