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!
You have two problems in your code:
foreach()
to an object.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()
.