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).
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)
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With