I would like to use the "foreach" loop in R (package foreach + doParallel) but in my work i found that the loop returns some NA and the classic "for" loop returns the value I want :
library(foreach)
library(doParallel)
ncore=as.numeric(Sys.getenv('NUMBER_OF_PROCESSORS'))-1
registerDoParallel(cores=ncore)
B=2
a = vector()
b = vector()
foreach(i = 1:B, .packages = "ez",.multicombine = T,.inorder = T, .combine = 'c')%dopar%{
a[i] = i + 1
return(a)
}
for(i in 1:B){
b[i] = i + 1
b
}
As you can see if you try it, the object "a" returns a vector with 2, NA and 3 while the object "b" returns 2 and 3 (that's what I want).
I actually can't understand why there's a "NA" in my results...
This is because
foreach
does not change the global objecta
. Try to combine withlist
. It will be easier to understand what is happening. I have increasedB
to3
.We can see that in each iteration an empty vector
a
is taken and one value of it is filled. If youc
combine the result you getNA
values.In this example you could do.