Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove matrix from a list of matrices

Tags:

r

I have a list of 12 matrices called M and I'm trying to remove every matrix from the list that has 0 rows.

I know that I can manually remove those matrices with (for example, to remove the second matrix) M[2] <- NULL. I would like to use logic to remove them with something like: M <- M[nrow(M)>0,] (but that obviously didn't work).

like image 905
littleisrael Avatar asked Apr 08 '21 19:04

littleisrael


Video Answer


2 Answers

Another option that could work is Filter in base R

Filter(nrow, M)

It works because 0 is considered as FALSE and all other values as TRUE

If there are also some attributes, gv from collapse could maintain it

library(collapse)
gv(M, function(x) nrow(x) > 0)
like image 99
akrun Avatar answered Oct 19 '22 18:10

akrun


Use sapply() to get a logical vector of non-zero matrices, then use that vector to select/subset:

nzm <- sapply(M, function(m) nrow(m)>0)
M <- M[nzm]
like image 5
Ben Bolker Avatar answered Oct 19 '22 20:10

Ben Bolker