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.
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[3,3]
be 35 instead of 34? – GKi