Home > Enterprise >  Counting diagonal sums in a matrix in R
Counting diagonal sums in a matrix in R

Time:06-05

I am working on a matrix that has different probabilities, and I would like to add the sums of different diagonals within the data table.

As an example with random numbers:

What I have:

df <- data.frame(`1` = c(1:5),
        `2` = c(1:5),
        `3` = c(1:5),
        `4` = c(1:5),
        `5` = c(1:5))

Table Output:

  X1 X2 X3 X4 X5
1  1  1  1  1  1
2  2  2  2  2  2
3  3  3  3  3  3
4  4  4  4  4  4
5  5  5  5  5  5

One diagonal I would like to be able to get the sum of (desired diagonal is in bold):

   X1 X2 X3 X4 X5
Y1  1  **1**  1  1  1
Y2  2  2  **2**  2  2
Y3  3  3  3  **3**  3
Y4  4  4  4  4  **4**
Y5  5  5  5  5  5

I could not seem to find anything on this, but if anyone has a solution or has a resource that would help me out, it would be appreciated.

CodePudding user response:

Perhaps this helps

sum(df[(col(df)-1) == row(df)])
[1] 10

The idea is to make use of col/row indexes. When we use col(df)-1, the index of 1 is shifted to right, where as the row(df) is not shifted

> col(df)-1
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    1    2    3    4
[2,]    0    1    2    3    4
[3,]    0    1    2    3    4
[4,]    0    1    2    3    4
[5,]    0    1    2    3    4
> row(df)
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    1    1    1    1
[2,]    2    2    2    2    2
[3,]    3    3    3    3    3
[4,]    4    4    4    4    4
[5,]    5    5    5    5    5
> (col(df)-1) == row(df)
      [,1]  [,2]  [,3]  [,4]  [,5]
[1,] FALSE  TRUE FALSE FALSE FALSE
[2,] FALSE FALSE  TRUE FALSE FALSE
[3,] FALSE FALSE FALSE  TRUE FALSE
[4,] FALSE FALSE FALSE FALSE  TRUE
[5,] FALSE FALSE FALSE FALSE FALSE

CodePudding user response:

Here is on more using diag:

Extract or replace the diagonal of a matrix, or construct a diagonal matrix.

sum(diag(as.matrix(df)-1))

[1] 10

CodePudding user response:

sum(diag(as.matrix(df)[, -c(1:n)])) where n is the number of columns to skip

  •  Tags:  
  • r
  • Related