The sum of some positions in a row - R

Given the general nxn matrix - for example:

A <- matrix(1:16, nrow = 4, ncol = 4)

How can I calculate the sum of the lines in the "lower right" triangle and show the information in a vector?

example

+6
source share
3 answers

Find a mask that encapsulates the desired data:

> 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 the 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
+6
source
A = matrix(1:16, 4)
A
#      [,1] [,2] [,3] [,4]
# [1,]    1    5    9   13
# [2,]    2    6   10   14
# [3,]    3    7   11   15
# [4,]    4    8   12   16

sapply(1:NROW(A), function(i) sum(tail(A[i,], i - 1)))
#[1]  0 14 26 36
+2
source

Here is the solution. The key is to use the function lower.trior upper.tri, and then use applyto sort each row or column. Finally, calculate the sum of each row.

# Create example data frame
m <- matrix(1:16, 4)
m
#      [,1] [,2] [,3] [,4]
# [1,]    1    5    9   13
# [2,]    2    6   10   14
# [3,]    3    7   11   15
# [4,]    4    8   12   16

# Calculate the sum 
rowSums(m * apply(lower.tri(m), 1, sort))
# [1] 0 14 26 36

rowSums(m * apply(upper.tri(m), 2, sort))
# [1] 0 14 26 36
+1
source

All Articles