Rlist: recursively filter list nodes with NA

Using the (preferably) rlist package, is there a way to filter out the nodes of a (multi-level) list so that the resulting list does not have NA values ​​at any level?

 library(rlist) devs <- list( p1=list(name="Ken",age=24, interest=c("reading","music","movies"), lang=list(r=NA,csharp=4)), # <------ NA here p2=list(name="James",age=25, interest=c("sports","music"), lang=list(r=3,java=2,cpp=5)), p3=list(name="Penny",age=NA, # <------ NA here interest=c("movies","reading"), lang=list(r=1,cpp=4,python=2))) 

In the above example, since the nodes p1 and p3 contain NA somewhere in their hierarchy, the expected list of results should be p2 . We do not know in advance the structure or names of the input list.

+5
source share
2 answers

list.search() recursively scans the list by condition and can be used to find NA in the children of devs .

Using pipeR and rlist together to make the code more understandable:

 devs %>>% list.filter(. %>>% list.search(anyNA(.)) %>>% length == 0L) 

This only highlights p2 .

This is almost a direct translation of your request :)

or an easier way -

 list.filter(devs, !anyNA(unlist(.))) 
+2
source

What about:

 # for every element in devs, does it have 0 NA elements when unlisted? sapply(devs, function(x) !anyNA(unlist(x))) 

which returns:

 p1 p2 p3 FALSE TRUE FALSE 

You can only get the list item you need with:

 devs[sapply(devs, function(x) !anyNA(unlist(x)))] 
+5
source

Source: https://habr.com/ru/post/1204649/


All Articles