1

When executing the following dummy code:

P = 2
library(foreach)
library(doMC)
registerDoMC(P)      
f = double(length = P)

print('=== f values in loop ===')
foreach(c = 1:P) %dopar% 
{
    f[c] = c
    print(f[c])
}

print('### f values after loop ###')
for(c in 1:P){ print(f[c])  }

I receive the following output:

"=== f values in loop ==="
1
2
"### f values after loop ###"
0
0

Why are the f values assigned in the foreach loop not saved?

In particular, why are f[1] and f[2] equal to zero after the foreach loop?

Thanks!

Andrie
  • 176,377
  • 47
  • 447
  • 496
user233558
  • 13
  • 4

1 Answers1

3

You have two problems in your code:

  1. You haven't assigned the result of the foreach() to an object.
  2. The foreach function doesn't return a value. (Strictly speaking, the function returns the value of print() which is NULL.)

Use

f <- foreach(c = 1:P) %dopar% { c }

The important difference between for() in base R and foreach() is that anything you do inside for() is available in the parent environment of for(). However, foreach() is a function and anything inside the foreach() function is local to the function environment.

In a sense, foreach() is more similar to lapply() than to for().

Andrie
  • 176,377
  • 47
  • 447
  • 496
  • Thanks Andrie, that worked out! Just one follow up question, how to assign two arguments (e.g. f and g) as output from foreach()? I am quite new to R. – user233558 Jul 26 '15 at 07:17
  • Nevermind, found it here: http://stackoverflow.com/questions/19791609/saving-multiple-outputs-of-foreach-dopar-loop – user233558 Jul 26 '15 at 07:36