Using foreach loop in r returning NA

假装没事ソ 提交于 2019-12-06 16:55:41

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

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

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