Home > front end >  In a list of matrices: keep the non-zero section in each matrix
In a list of matrices: keep the non-zero section in each matrix

Time:05-21

I have a list of matrices varying in dimension and each matrix has one all-zero row or column or an all-zero column and an all-zero row. I believe there should be an efficient, one-liner to trim them down to only non-zero but I haven't found it.

dput(mt)
list(A = structure(c(1, 7, 9, 0, 3, 4, 1, 0, 0, 0, 0, 0), dim = 4:3), 
    B = structure(c(1, 0, 3, 0, 8, 0, 2, 0), dim = c(2L, 4L)), 
    C = structure(c(1, 3, 8, 2, 0, 0, 0, 0), dim = c(4L, 2L)))

My expected result looks like this

    $A
     [,1] [,2]
[1,]    1    3
[2,]    7    4
[3,]    9    1

$B
     [,1] [,2] [,3] [,4]
[1,]    1    3    8    2

$C
     [,1]
[1,]    1
[2,]    3
[3,]    8
[4,]    2

CodePudding user response:

We can create row/column indexing where the rows are all 0 or columns are all 0 with rowSums/colSums on a logical matrix and then create a logical vector for the row/column index

lapply(mt, function(x)
    {
      m1 <- x == 0
      x[!(rowSums(m1)== ncol(m1)), 
      !(colSums(m1) == nrow(m1)),drop = FALSE]
     }
 )

-output

$A
     [,1] [,2]
[1,]    1    3
[2,]    7    4
[3,]    9    1

$B
     [,1] [,2] [,3] [,4]
[1,]    1    3    8    2

$C
     [,1]
[1,]    1
[2,]    3
[3,]    8
[4,]    2
  • Related