R中并行的上对角线计算

Upper diagonal calculation in parallel in R

我使用以下代码:

  library(foreach)
  library(doParallel)
  N<-5
  cl<-makeCluster(8)
  registerDoParallel(cl)

  #loop
  s8 <- foreach(i=1:N, .combine='rbind') %:%
    foreach(j=1:N, .combine='c') %dopar% {

        dis <-as.numeric (i+j)  } ## In reality there something more complicated

  stopCluster(cl) 

我得到以下结果:

> s8
         [,1] [,2] [,3] [,4] [,5]
result.1    2    3    4    5    6
result.2    3    4    5    6    7
result.3    4    5    6    7    8
result.4    5    6    7    8    9
result.5    6    7    8    9   10 

我想得到上对角矩阵如下:

> s8
         [,1] [,2] [,3] [,4] [,5]
result.1    2    3    4    5    6
result.2    0    4    5    6    7
result.3    0    0    6    7    8
result.4    0    0    0    8    9
result.5    0    0    0    0   10

如果我把内循环的迭代器改成

foreach(j=i:N, .combine='c') %dopar% {

我没有得到所需的结果。

也许这样(虽然我可能只会并行化外循环):

library(foreach)
library(doParallel)
N<-5
cl<-makeCluster(4)
registerDoParallel(cl)

#loop
#result is a list of vectors
s8 <- foreach(i=1:N) %:%
  foreach(j=i:N, .combine='c') %dopar% {

    as.numeric (i+j)  } ## In reality there something more complicated

stopCluster(cl) 

Post-处理以获得相同的长度:

s8 <- t(vapply(s8, function(x) {
  x <- rev(x)
  length(x) <- N
  rev(x)
}, FUN.VALUE = numeric(N)))

s8[lower.tri(s8)] <- 0

#     [,1] [,2] [,3] [,4] [,5]
#[1,]    2    3    4    5    6
#[2,]    0    4    5    6    7
#[3,]    0    0    6    7    8
#[4,]    0    0    0    8    9
#[5,]    0    0    0    0   10