Reputation: 1801
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.
Upvotes: 1
Views: 151
Reputation: 39667
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])))
Upvotes: 4
Reputation: 389047
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])
Upvotes: 2