R: How to sum pairs in a Matrix by row?

前端 未结 5 727
臣服心动
臣服心动 2021-01-23 02:54

Probably this would be easy. I have a Matrix:

testM <- matrix(1:40, ncol = 4, byrow = FALSE)
testM
      [,1] [,2] [,3] [,4]
 [1,]    1   11   21   31
 [2,]           


        
5条回答
  •  说谎
    说谎 (楼主)
    2021-01-23 03:38

    We can do a matrix multiplication:

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

    another solution with tapply():

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

提交回复
热议问题