R中的嵌套foreach循环以更新公共数组 [英] nested foreach loops in R to update common array
问题描述
我试图在 R 中使用几个 foreach 循环来并行填充一个公共数组.我正在尝试做的一个非常简化的版本是:
I am trying to use a couple of foreach loops in R to fill out a common array in parallel. A very simplified version of what I am trying to do is:
library(foreach)
set.seed(123)
x <- matrix(NA, nrow = 8, ncol = 2)
foreach(i=1:8) %dopar% {
foreach(j=1:2) %do% {
l <- runif(1, i, 100)
x[i,j] <- i + j + l #This is much more complicated in my real code.
}
}
我想编写代码以并行更新矩阵 x
并使输出看起来像:
I would like to code to update the matrix x
in parallel and have the output look like:
> x
[,1] [,2]
[1,] 31.47017 82.04221
[2,] 45.07974 92.53571
[3,] 98.22533 12.41898
[4,] 59.69813 95.67223
[5,] 63.38633 55.37840
[6,] 102.94233 56.61341
[7,] 78.01407 69.25491
[8,] 26.46907 100.78390
但是,我似乎无法弄清楚如何更新数组.我曾尝试将 x <-
放在别处,但它似乎不喜欢它.我认为这将是一件很容易解决的事情,但我所有的搜索还没有把我带到那里.谢谢.
However, I cannot seem to figure out how to get the array to be updated. I have tried putting the x <-
elsewhere, but it doesn't seem to like it. I think this will be a very easy thing to fix, but all my searching has not lead me there yet. Thanks.
推荐答案
foreach
循环用于返回值,例如 lapply
.通过这种方式,它们与用于其副作用的 for
循环非常不同.通过使用适当的 .combine
函数,内部 foreach
循环可以返回向量,这些向量通过外部 foreach
循环按行组合成矩阵:
foreach
loops are used for their return value, like lapply
. In this way they are very different from for
loops which are used for their side effects. By using the appropriate .combine
functions, the inner foreach
loop can return vectors which are combined row-wise into a matrix by the outer foreach
loop:
x <- foreach(i=1:8, .combine='rbind') %dopar% {
foreach(j=1:2, .combine='c') %do% {
l <- runif(1, i, 100)
i + j + l
}
}
您也可以使用嵌套运算符:%:%
:
You can also use the nesting operator: %:%
:
x <- foreach(i=1:8, .combine='rbind') %:%
foreach(j=1:2, .combine='c') %dopar% {
l <- runif(1, i, 100)
i + j + l
}
注意 set.seed
可能不会做你想做的,因为它是在本地机器上执行的,而随机数是在不同的 R 会话中生成的,可能在不同的机器上.
Note that set.seed
probably won't do what you want, since it is being performed on the local machine, while the random numbers are generated in different R sessions, possibly on different machines.
这篇关于R中的嵌套foreach循环以更新公共数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!