Michael
Michael

Reputation: 575

Sum two rows in a matrix

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

Answers (2)

Karolis Koncevičius
Karolis Koncevičius

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

Ronak Shah
Ronak Shah

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

Related Questions