bartektartanus
bartektartanus

Reputation: 16080

Row sums of matrix over/under diagonal

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.

Upvotes: 2

Views: 797

Answers (1)

alexis_laz
alexis_laz

Reputation: 13122

A way:

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

Upvotes: 4

Related Questions