Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In a list of matrices: keep the non-zero section in each matrix

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading