1
library(foreach)
library(doMPI)

m<-matrix(as.integer(0),5,5)

cl <- startMPIcluster(count=4)
registerDoMPI(cl)

foreach(b=1:5)%dopar%
  {
    m[b,]<-c(1:5)
  }

在 R 上运行上面的代码,我得到了较低的结果。

> m
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    0    0    0
[2,]    0    0    0    0    0
[3,]    0    0    0    0    0
[4,]    0    0    0    0    0
[5,]    0    0    0    0    0

我怎样才能得到矩阵应用于逐行替换?

4

1 回答 1

1

The purpose of foreach and %dopar% isn't to modify objects in environments of the R process that created the cluster. What those functions are primarily used for is doing some processing and returning the value of the last evaluated expression.

So instead,

mNew <- foreach(b=1:5, .combine = rbind) %dopar%
{
  c(1:5)
}

Or if you only want to "replace" certain elements from the original matrix,

mNew <- foreach(b=1:5, .combine = rbind) %dopar%
{
  c(m[b, seq_len(b)], seq_len(5)[seq_len(5 - b)])
}
于 2012-11-21T23:17:32.560 回答