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

强颜欢笑 提交于 2019-12-02 02:49:30

问题


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,]    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

and I want to "reduce" the matrix summing column pairs by row. Expected result:

      [,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

I tried this but doesn't work

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

回答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



回答2:


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]) )



回答3:


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))



回答4:


How about:

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



回答5:


a solution around your initial idea:

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


来源:https://stackoverflow.com/questions/36432686/r-how-to-sum-pairs-in-a-matrix-by-row

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!