1
votes

I want to sum multiple column values (in a matrix) and collapse them into a new matrix with fewer columns but maintain the same number of rows as in the original matrix. Below is my example:

I want to sum the values of column 1 and 3 and collapse them into a new column (say column n1), sum the values of column 2 and 4 and collapse them into a new column (say column n2), sum the values of column 5 and 6 and collapse them into a new column (say column n3):

mat1 <- matrix(c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18), nrow = 3, ncol = 6, byrow = TRUE)

 [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    2    3    4    5    6
[2,]    7    8    9   10   11   12
[3,]   13   14   15   16   17   18

So the desired output will be

     [,1] [,2] [,3]
[1,]    4   16   28
[2,]    6   18   30
[3,]   11   23   34

Any way I can efficiently achieve this? Thanks.

2
1. In input you have shown only 5 columns but you have 6 columns in mat1. 2. Input and output don't match as per your description. You say you want to add column 1 and column 3 and show the output as 4, 6 and 11 but column 1 + column 3 is 4, 16 and 28.Ronak Shah
@Ronak Thanks for noting the mismatch in column numberChris T.
Do you want the output transposed? Shouldn't be the number at [3,3] be 35 instead of 34?GKi
@GKi nope, it doesn't need to be transposed.Chris T.

2 Answers

2
votes

If there is no sequence or logic involved in selection of columns you need to add them manually and cbind :

cbind(mat1[, 1] + mat1[, 3], mat1[, 2] + mat1[, 4], mat1[, 5] + mat1[, 6])
4
votes

You can store the paired rows in an index and use this for subseting when calculating rowSums:

idx <- matrix(c(1,3,2,4,5,6), 2)
t(apply(idx, 2, function(i) rowSums(mat1[,i])))
#     [,1] [,2] [,3]
#[1,]    4   16   28
#[2,]    6   18   30
#[3,]   11   23   35

In case you want to select not only 2 columns you can store the indices in a list.

idx <- list(c(1,3), c(2,4), c(5,6))
t(sapply(idx, function(i) rowSums(mat1[,i])))