Reputation: 575
Consider the following matrix:
mat <- cbind(c(5,2,5),c(6,3,2))
I want to sum the two first rows, so I get the following matrix:
7 9
5 2
How do I do that in R?
Upvotes: 0
Views: 922
Reputation: 9656
You should use rowsum
:
> rowsum(mat, c(1,1,2))
[,1] [,2]
1 7 9
2 5 2
The first argument is your matrix mat
, the second one specifies how the rows should be grouped together. Here c(1,1,2)
specify that first two rows are in one group (and summed together) and the third row is in another group.
Note: Do not confuse this with rowSums
- a different function.
Upvotes: 3
Reputation: 388982
We can use colSums
to sum first n
rows and rbind
remaining ones
n <- 2
rbind(colSums(mat[seq_len(n), ]), mat[(n + 1):nrow(mat), ])
# [,1] [,2]
#[1,] 7 9
#[2,] 5 2
Upvotes: 2