7

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?

1 Answer 1

13

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)
}
Sign up to request clarification or add additional context in comments.

2 Comments

similar, but the other way around: myf = function(x) if (length(x)>0){lapply(x, myf)} else {if(length(x)==0) "" else x} and lapply(nested_list, myf)
Thanks guys! calling the function inside same function.. never thought of that :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.