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

前端 未结 5 737
臣服心动
臣服心动 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:18

    a solution around your initial idea:

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

提交回复
热议问题