0

我有一个a缺失值的向量(缺失值为 5,可能还有更多缺失值)。我想s并行创建上三角数据框(矩阵)。最终的数据帧s应该是基于a索引的b

> s
   1  2  3  4   6
1 22 32 42 52  82
2  0 42 52 62  92
3  0  0 62 72 102
4  0  0  0 82 112
6  0  0  0  0 142

我使用以下代码:

library(foreach)
library(doParallel)

    b<-c(11,21,31,41,61)
    a<-c(1,2,3,4,6)
    N<-length (a)
    cl<-makeCluster(4)
    registerDoParallel(cl)

    #loop
    #result is a list of vectors
    s <- foreach(i=a) %:%
      foreach(j=i:N, .combine='c') %dopar% {
        as.numeric(b[i]+b[j])  } 


    stopCluster(cl)

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

    s[lower.tri(s)] <- 0
4

2 回答 2

1

使用该outer函数的简单方法。

x <- 1:6
a <- outer(x, x, "+")
b <- a[-5, -5]
b[lower.tri(b)] <- 0
b
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    2    3    4    5    7
# [2,]    0    4    5    6    8
# [3,]    0    0    6    7    9
# [4,]    0    0    0    8   10
# [5,]    0    0    0    0   12

更新:

如果您不想提前构建整个矩阵,请提前从向量x中删除缺失值即可。

x <- c(1:4, 6)
a <- outer(x, x, "+")
a[lower.tri(a)] <- 0
a
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    2    3    4    5    7
# [2,]    0    4    5    6    8
# [3,]    0    0    6    7    9
# [4,]    0    0    0    8   10
# [5,]    0    0    0    0   12
于 2016-04-27T08:05:06.043 回答
0

这是解决方案:

library(foreach)
library(doParallel)

       b<-c(11,21,31,41,61,71)
        a<-c(1,2,3,4,6)
        N<-length (a)
        cl<-makeCluster(4)
        registerDoParallel(cl)

        #loop
        #result is a list of vectors
        s <- foreach(i=a) %:%
          foreach(j=a[i:N], .combine='c') %dopar% {
            as.numeric(b[i]+b[j])  } 


        stopCluster(cl)

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

        s[lower.tri(s)] <- 0
    s<-as.data.frame(s)
    colnames(s)<-a
    rownames (s)<-a

    > s
       1  2  3  4   6
    1 22 32 42 52  82
    2  0 42 52 62  92
    3  0  0 62 72 102
    4  0  0  0 82 112
    6  0  0  0  0 142
于 2016-04-27T10:03:19.587 回答