Loop nested lists in R

I have a huge nested list of 15 levels. I need to replace empty lists occurring at any level with chr "". I tried iterating over the list, but it does not work. is there an easy way to do this?

nested_list<-list(a=list(x=list(),y=list(i=list(),j=list(p=list(),q=list()))),b=list())

lapply(nested_list,function(x) if(length(x)==0) "" else x)

lapply applies only to the first level, how do I recursively iterate over the entire nested list and perform this action?

+4
source share
1 answer

Try the following recursion.

foo <- function(l){
    lapply(l, function(x) if(length(x)==0) "" else foo(x))
}
foo(nested_list)

EDIT : best version

foo <- function(l){
    lapply(l, function(x) if(is.list(x) && length(x)==0) "" else if(is.list(x)) foo(x) else x)
}
+7
source

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


All Articles