【问题标题】:R: How to sum pairs in a Matrix by row?R:如何按行对矩阵中的对求和?
【发布时间】:2016-07-25 18:25:06
【问题描述】:

这可能很容易。我有一个矩阵:

testM <- matrix(1:40, ncol = 4, byrow = FALSE)
testM
      [,1] [,2] [,3] [,4]
 [1,]    1   11   21   31
 [2,]    2   12   22   32
 [3,]    3   13   23   33
 [4,]    4   14   24   34
 [5,]    5   15   25   35
 [6,]    6   16   26   36
 [7,]    7   17   27   37
 [8,]    8   18   28   38
 [9,]    9   19   29   39
[10,]   10   20   30   40

我想逐行“减少”矩阵求和列对。预期结果:

      [,1] [,2]
 [1,]   12   52
 [2,]   14   54
 [3,]   16   56
 [4,]   18   58
 [5,]   20   60
 [6,]   22   62
 [7,]   24   64
 [8,]   26   66
 [9,]   28   68
[10,]   30   70

我试过了,但没有用

X <- apply(1:(ncol(testM)/2), 1, function(x) sum(testM[x], testM[x+1]) )

Error in apply(1:(ncol(testM)/2), 1, function(x) sum(testM[x], testM[x +  : 
  dim(X) must have a positive length

【问题讨论】:

    标签: r lapply sapply


    【解决方案1】:
    testM[,c(T,F)]+testM[,c(F,T)];
    ##       [,1] [,2]
    ##  [1,]   12   52
    ##  [2,]   14   54
    ##  [3,]   16   56
    ##  [4,]   18   58
    ##  [5,]   20   60
    ##  [6,]   22   62
    ##  [7,]   24   64
    ##  [8,]   26   66
    ##  [9,]   28   68
    ## [10,]   30   70
    

    【讨论】:

    • testM[, seq(1, ncol(testM), by=2)] + testM[, seq(2, ncol(testM), by=2)] 与列的显式索引类似。
    【解决方案2】:

    这是使用rowSums()的解决方案

    sapply( list(1:2,3:4) , function(i) rowSums(testM[,i]) )
    

    如果列数应该是任意的,那就更复杂了:

    li <- split( 1:ncol(testM) , rep(1:(ncol(testM)/2), times=1 , each=2))
    
    sapply( li , function(i) rowSums(testM[,i]) )
    

    【讨论】:

    • @Frank:是的,我为这种情况添加了解决方案。
    • rowsum 提供了另一种(通常是快速的)替代方案。t(rowsum(t(testM), rep(1:2, each=2))) ,其中第二个 (group ) 参数可用于对任意列求和。
    【解决方案3】:

    我们可以做矩阵乘法:

    M <- matrix(c(1,1,0,0, 0,0,1,1), 4, 2)
    testM %*% M
    

    tapply() 的另一个解决方案:

    g <- gl(ncol(testM)/2, 2)
    t(apply(testM, 1, FUN=tapply, INDEX=g, sum))
    

    【讨论】:

      【解决方案4】:

      怎么样:

      matrix(c(testM[, 1] + testM[, 2], testM[, 2] + testM[, 4]), nrow = 10)
      

      【讨论】:

      • testM[, c(1,3)] + testM[, c(2,4)] 是一样的。
      【解决方案5】:

      围绕您最初想法的解决方案:

      sapply(seq(2, ncol(testM), 2), function(x) apply(testM[, (x-1):x], 1, sum))
      

      【讨论】:

        猜你喜欢
        • 2020-06-20
        • 1970-01-01
        • 2019-06-21
        • 2015-06-10
        • 1970-01-01
        • 1970-01-01
        • 2020-08-26
        • 2017-06-01
        相关资源
        最近更新 更多