I have a huge nested list of 15 levels. i need to replace empty lists occurring at any level with chr "". I tried lapply to loop through the list but it's not working. is there any 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)
the lapply is being applied to only first level, how do i recursively loop the entire nested list and perform this action?
The lapply() function does the following simple series of operations: it loops over a list, iterating over each element in that list.
frame() converts the nested list to an R DataFrame by taking do. call() function as a parameter. So each list inside a nested list will be a column in a DataFrame. So the column names in the DataFrame will be nested list names.
A list that occurs as an element of another list (which may ofcourse itself be an element of another list etc) is known as nested list.
Try the following recursion.
foo <- function(l){
lapply(l, function(x) if(length(x)==0) "" else foo(x))
}
foo(nested_list)
EDIT: A better version
foo <- function(l){
lapply(l, function(x) if(is.list(x) && length(x)==0) "" else if(is.list(x)) foo(x) else x)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With