Considering a generic matrix nxn - for example:
A <- matrix(1:16, nrow = 4, ncol = 4)
How can I calculate the sum of the rows in the "right lower" triangle and show the information in a vector?
Find a mask that encapsulates the data desired:
> mask <- apply(lower.tri(A, diag = FALSE), 1, rev)
> mask
[,1] [,2] [,3] [,4]
[1,] FALSE FALSE FALSE FALSE
[2,] FALSE FALSE FALSE TRUE
[3,] FALSE FALSE TRUE TRUE
[4,] FALSE TRUE TRUE TRUE
Multiply this mask and calculate sums:
> A * mask
[,1] [,2] [,3] [,4]
[1,] 0 0 0 0
[2,] 0 0 0 14
[3,] 0 0 11 15
[4,] 0 8 12 16
> rowSums(A * mask)
[1] 0 14 26 36
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With