Using foreach loop in r returning NA

971 views Asked by At

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...

2

There are 2 answers

1
djhurio On BEST ANSWER

This is because foreach does not change the global object a. Try to combine with list. It will be easier to understand what is happening. I have increased B to 3.

> B=3
> 
> a = vector()
> 
> foreach(i = 1:B, .multicombine = T, .inorder = T, .combine = 'list') %dopar% {
+   a[i] = i + 1
+   return(a)
+ }
[[1]]
[1] 2

[[2]]
[1] NA  3

[[3]]
[1] NA NA  4

We can see that in each iteration an empty vector a is taken and one value of it is filled. If you c combine the result you get NA values.

> foreach(i = 1:B, .multicombine = T, .inorder = T, .combine = 'c') %dopar% {
+   a[i] = i + 1
+   return(a)
+ }
[1]  2 NA  3 NA NA  4

In this example you could do.

> a <- foreach(i = 1:B, .multicombine = T, .inorder = T, .combine = 'c') %dopar% {
+   i + 1
+ }
> a
[1] 2 3 4
0
F. Privé On

foreach works more like lapply than a for-loop.

You can simply do foreach(i = 1:B, .combine = 'c') %dopar% { i + 1 } (.multicombine and .inorder are already TRUE but you may want to set .maxcombine to a high value).