Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with sapply when determining if nested list has all NA values in R

Tags:

r

I have a nested list (or list of lists) with NA randomly allocated values. I am trying to determine if the nested list contains all NA values. For example:

#Example list with NA values
L.miss<-list(list(NA,NA,c(NA,NA,NA),c(NA,NA)),list(1,6,c(0,3,NA,0,NA,0),c(0,NA,0,1,0,0),1,NA,c(0,1),2,c(0,0)),
             list(NA,NA),list(1,0),list(1,NA,c(NA,0,0,0),c(NA,NA),c(1,0,0,NA,0),0))

Here, L.miss[[1]] and L.miss[[3]] contain all NA values. When I try:

all.NA<-sapply(L.miss, function(x) all(is.na(x)))

it returns a logical vector [1] FALSE FALSE TRUE FALSE FALSE. The desired output would be [1] TRUE FALSE TRUE FALSE FALSE since positions L.miss[[1]] and L.miss[[3]] contain vectors of all NA. I have tried lapply and rapply in the same function but does not work, and an exhaustive internet search doesn't provide much help. I am not sure why it is picking up the [[3]] position and not the [[1]] position. Any advice would be appreciated!

like image 250
jpsmith Avatar asked Nov 22 '19 16:11

jpsmith


2 Answers

unlist the nested lists, then test:

all.NA<-sapply(L.miss, function(x) all(is.na(unlist(x))))
like image 145
SmokeyShakers Avatar answered Nov 15 '22 07:11

SmokeyShakers


You need to apply all(is.na()) to the nested lists:

all.NA <- sapply(L.miss, function(x) all(sapply(x, function(y) all(is.na(y)))))
like image 41
Fino Avatar answered Nov 15 '22 08:11

Fino