how to see if any element of a list contains only a certain value in R

Viewed 221

I have a list of many matrices, let say my_list. I want to check if any of those matrices has only zero s as its element and if so which matrix in that list has such situation.

library(R.utils)
output_vec <- vector()
for(i in 1:length(my_list)){
   asZero(as.vector(my_list[[i]]))}

this gives me true falses but, I am not able to return the index of matrices with all zero elements. I appreciate any help with this.

2 Answers

We may need to wrap with all - loop over the list of matrices with sapply, create a logical expression (x == 0), wrap with all to return a single TRUE/FALSE - if all values excluding NAs (na.rm = TRUE) are 0, this returns TRUE or else FALSe

sapply(my_list, function(x) all(x == 0, na.rm = TRUE))

You can use norm to judge if all entries in the matrix is zeros, e.g.,

sapply(my_list, norm) == 0

since the norm of matrix is 0 if and only if all values are zeros.


Example

> my_list
[[1]]
     [,1] [,2] [,3]
[1,]    0    0    0
[2,]    0    0    0
[3,]    0    0    0

[[2]]
     [,1] [,2]
[1,]    1    1
[2,]    0    0


> sapply(my_list, norm) == 0
[1]  TRUE FALSE
Related