1
votes

With R: If I have a square matrix, what would be the easiest(as well as fast) way to delete the row and column if the value on the diagonal is less than five? For example

       x1  x2  x3  x4
    x1 13  15  12  25
    x2 23  4   23  34
    x3 21  11  1   11
    x4 11  22  23  33

The code would delete row 2 and column 2, and row 3 and column 3. I tried doing for(i in 1:nrow(Mx)), but deleting rows changes the total number of rows.

The final matrix would look like

       x1  x4
    x1 13  25
    x4 11  33
2

2 Answers

5
votes

Use the diag function and logical comparison with < and the [ subset operator like this...

idx <- ! diag(m) < 5
m <- m[ idx , idx ]

e.g.

m
#   x1 x2 x3 x4
#x1 13 15 12 25
#x2 23  4 23 34
#x3 21 11  1 11
#x4 11 22 23 33

idx <- ! diag(m) < 5    
m <- m[ idx , idx ]

m
#   x1 x4
#x1 13 25
#x4 11 33
0
votes

Not the more elegant or fastest solution, but it works

mat <- matrix(c(13, 23, 21, 11, 15, 4, 11, 22, 12, 23,
                1, 23, 25, 34, 11, 33), nrow = 4)

ind <- which(diag(diag(mat)) > 5, arr.ind = TRUE)

mat[ind[,1], ind[,2]]
##      [,1] [,2]
## [1,]   13   25
## [2,]   11   33