Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of some positions in a row - R

Tags:

r

matrix

sum

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?

example

like image 628
António Cruz Avatar asked Dec 09 '17 19:12

António Cruz


1 Answers

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
like image 176
saladi Avatar answered Oct 02 '22 20:10

saladi