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

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

    Here's a solution using rowSums()

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

    if the number of columns should be arbitrary, it gets more complicated:

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

提交回复
热议问题