【问题标题】:using the foreach loop and combining using a function in r使用 foreach 循环并使用 r 中的函数进行组合
【发布时间】:2015-01-29 06:54:54
【问题描述】:

我正在阅读 r 中 foreach 包的文档,并且能够理解 .combine 是如何在 crbindcbind 上完成的。但是文档说,如果您想使用此函数进行组合,您也可以将函数的名称传递给语句中的.combine。尝试访问我正在组合的此函数中每个 foreach 的各个元素时,我无法理解输出。 (让我把这个函数称为mycombinefunc

这是我尝试过的。我不明白为什么在 foreach 语句的输出中会打印两次输出。

> mycombinefunc= function(...){mylist = list(...);print(mylist)}

> foreach(i=1:2, .combine='mycombinefunc') %do% {c(1:5)}
[[1]]
[1] 1 2 3 4 5

[[2]]
[1] 1 2 3 4 5

[[1]]
[1] 1 2 3 4 5

[[2]]
[1] 1 2 3 4 5

#just calling the function directly to show what the expected output for one iteration of the foreach loop looks like. I would have expected that the above function call would produce two copies of the below output
> mycombinefunc(c(1:5))
[[1]]
[1] 1 2 3 4 5

【问题讨论】:

    标签: r parallel-foreach


    【解决方案1】:

    运行 combine 函数以将新结果合并到以前的结果。在您的示例中,您看到了两次输出,因为您在 combine 函数中明确有一个 print() 语句,因此您可以看到传递给 combine 函数的两个向量。然后,这个值从 foreach() 中返回,默认情况下 R 会将该函数的结果打印到控制台。

    您应该期望您的combine 收到两个值。上一次迭代和当前迭代中的一个。所以真正被调用的是

    mycombinefunc(1:5, 1:5)
    

    并且您应该将其“组合”成一个结果。这与 R 中的 Reduce() 函数的工作方式非常相似。或许可以查看?Reduce 帮助页面了解更多信息。

    假设你想要一个合并向量的函数,你可以这样做

    mycombinefunc= function(a,b){a+b}
    foreach(i=1:3, .combine='mycombinefunc') %do% {c(1:5)} 
    # [1]  3  6  9 12 15
    

    注意我们如何从foreach() 返回一个结果。我们没有看到任何中间值,因为我们从 combine 函数中删除了 print()。此外,我们得到的是单个向量而不是列表,因为我们选择将元素添加在一起而不是附加到列表中。

    【讨论】:

      猜你喜欢
      • 2013-05-03
      • 2018-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-24
      相关资源
      最近更新 更多