在返回NA的R中使用foreach循环 [英] Using foreach loop in r returning NA

查看:135
本文介绍了在返回NA的R中使用foreach循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在R中使用"foreach"循环(包foreach + doParallel),但是在我的工作中我发现该循环返回一些NA,而经典的"for"循环返回我想要的值:

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
      }

您可以看到是否尝试过,对象"a"返回一个具有2,NA和3的向量,而对象"b"则返回了2和3(这就是我想要的).

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

我实际上不明白为什么我的结果中会有一个"NA" ...

I actually can't understand why there's a "NA" in my results...

推荐答案

这是因为foreach不会更改全局对象a.尝试与list结合使用.将会更容易了解正在发生的事情.我已经将B增加到了3.

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

我们可以看到,在每次迭代中,都会提取空向量a并填充其中一个值.如果您c合并结果,则会得到NA值.

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

这篇关于在返回NA的R中使用foreach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆