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()
Mrflick
source share