Search for empty lists in a nested list of lists

Given a randomly nested list, how can I find if the list contains empty lists? Consider the following example:

mylist <- list(list("foo", "bar", "baz", list(list())))

I tried rapply , but this skips the lists. Although I could use lapply , I needed to know the level of nesting in advance. For this exercise, I don’t need to know where the list is (although it will be a bonus), I just need a way to determine if it is.

+8
r nested-lists
source share
2 answers

How about a function like this

 has_empty_list <- function(x) { if(is.list(x)) { if (length(x)==0) { return(TRUE) } else { return(any(vapply(x, has_empty_list, logical(1)))) } } else { return(FALSE) } } 

Basically, we create a recursive function to search for lists of length 0.

 has_empty_list( list(list("foo", "bar", "baz", list(list()))) ) # TRUE has_empty_list( list(list("foo", "bar", "baz", list(list(4)))) ) # FALSE 

And here is a modification to search for an empty list index

 find_empty_list <- function(x, index=c()) { if(is.list(x)) { #list if (length(x)==0) { if (length(index)==0) { return(0) } else { return(index) } } else { m <- Map(find_empty_list, x, lapply(seq_along(x), function(i) append(index,i))) # return the most deeply nested return( m[[which.max(lengths(m))]] ) } } else { return(numeric()) } } 

This should return an index vector that you can use to find the empty list. for example

 ( i <- find_empty_list(mylist) ) # [1] 1 4 1 mylist[[i]] # list() 

If the first parameter is an empty list, it will return 0

 find_empty_list(list()) # 0 

and if there is no empty list, it should return an empty vector

 find_empty_list(list(1:3, list("c", a~b))) # numeric() 
+8
source share

Another convenient option for working with a nested list is to use the data.tree package:

 library(data.tree) nodes <- as.Node(mylist) any(node$Get(function(node) length(as.list(node))) == 0) # [1] TRUE 
+5
source share

All Articles