Using foreach loop in r returning NA

喜你入骨 提交于 2019-12-10 11:44:36

问题


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


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/45919852/using-foreach-loop-in-r-returning-na

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!