Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

looping nested lists in R

Tags:

loops

list

r

lapply

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?

like image 487
JHS Avatar asked Apr 23 '15 09:04

JHS


People also ask

Can you loop through a list in R?

The lapply() function does the following simple series of operations: it loops over a list, iterating over each element in that list.

How do I convert a nested list to a DataFrame in R?

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.

What is a nested list?

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.


1 Answers

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)
}
like image 176
Randy Lai Avatar answered Sep 20 '22 05:09

Randy Lai