【问题标题】:R: parallelization with foreachR:与 foreach 并行化
【发布时间】:2016-07-11 11:05:52
【问题描述】:

我是 R 新手。我编写了这个非常简单的脚本来突出我的问题。如果我运行这个常规的 for 循环,测试数据会在每次迭代时按照我想要的方式更新。

a = 5
b = 4
c = 3
testdata = matrix(nrow=100, ncol=5)
for(j in 1:100){
testdata[j,1] <- a*j
testdata[j,2] <- b*j
testdata[j,3] <- c*j
testdata[j,4] <- (a+b)*j
testdata[j,5] <- (a+c)*j
}

然而,这个使用 foreach 的并行版本完成了计算,但它们没有在 testdata 中更新。

a = 5
b = 4
c = 3
testdata = matrix(nrow=100, ncol=5)
library(foreach)
library(doParallel)
library(doMC)
registerDoMC()
getDoParWorkers()  # Checking the number of cores. 

foreach(j = 1:100) %dopar% {
  testdata[j,1] <- a*j
  testdata[j,2] <- b*j
  testdata[j,3] <- c*j
  testdata[j,4] <- (a+b)*j
  testdata[j,5] <- (a+c)*j
}

我曾尝试在这里和互联网上的其他地方学习示例,但大多数示例在 R shoptalk 中太深入了,我无法理解。我怎样才能让这个并行版本做非并行版本做的事情。谢谢。

【问题讨论】:

  • 看看.combine 参数。

标签: r parallel-processing domc doparallel


【解决方案1】:

您应该查看foreach 包的文档。在代码的foreach(j = 100) 部分,您可以指定参数.combine 来告诉foreach 如何编译您的结果。由于您想要一个 5x100 的数据框/矩阵,因此您可以在逻辑上编写一个包含五个参数的向量(即c(a*j, b*j, c*j, (a+b)*j, (a+c)*j)),然后将rbind 它们组成一个数据框。在下面查看我的代码:

a = 5
b = 4
c = 3

library(foreach)
library(doParallel) 
library(parallel)

## Assuming you want to use all of your cores
registerDoParallel(cores = detectCores())

## Specify your .combine argument below
foreach(j = 1:100, .combine = "rbind") %dopar% {
    c(a*j, b*j, c*j, (a+b)*j, (a+c)*j)
}

这会吐出来:

           [,1] [,2] [,3] [,4] [,5]
result.1      5    4    3    9    8
result.2     10    8    6   18   16
result.3     15   12    9   27   24
result.4     20   16   12   36   32
result.5     25   20   15   45   40
...

然后您可以通过将其分配给您想要的变量来更进一步:

...
testdata <- foreach(j = 1:100, .combine = "rbind") %dopar% {
                c(a*j, b*j, c*j, (a+b)*j, (a+c)*j)
            }
testdata <- as.data.frame(testdata, row.names = FALSE)

希望这会有所帮助!

【讨论】:

  • 漂亮!正是我需要的。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-27
  • 2011-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-19
  • 2015-09-28
相关资源
最近更新 更多