2
votes

I want to calculate row/col sums for upper/lower triangle matrix (with diagonal). Example:

m <- matrix(1:9, nrow=3)
#result:
upperRowSums(m)
## [1] 12 13 9
lowerRowSums(m)
## [1] 1 7 18

I know that this could be done with simple for loop, but I want to avoid this. I'm looking for pure R solution.

1

1 Answers

4
votes

A way:

rowSums(m * upper.tri(m, diag=TRUE))
#[1] 12 13  9