1

Say I have a nested list like this

lst <- list(a=list(b=list("a", "b")), c=list("d"))
str(lst)
#List of 2
# $ a:List of 1
#  ..$ b:List of 2
#  .. ..$ : chr "a"
#  .. ..$ : chr "b"
# $ c:List of 1
#  ..$ : chr "d"

and I want to remove all the elements that don't match a vector of names (characters here), but I also want to remove the entire nested component if there are no matches. So, for example, using rapply I have this

## Just keep the branches that have an "a" value
keeps <- "a"

## Pass this function to rapply
f <- function(x) if(any(unlist(x) %in% keeps)) x else NULL
res <- rapply(lst, f, how="replace")

str(res)
# List of 2
# $ a:List of 1
#  ..$ b:List of 2
#  .. ..$ : chr "a"
#  .. ..$ : NULL
# $ c:List of 1
#  ..$ : NULL

So, I would have liked the entire c list to be cleaved. I don't think I can do this with a single rapply operation? If not, what would be a good way to do this.

Rorschach
  • 31,301
  • 5
  • 78
  • 129
  • [this](http://stackoverflow.com/questions/26539441/r-remove-null-elements-from-list-of-lists) or [this](http://stackoverflow.com/questions/25081263/is-there-a-super-fast-way-to-remove-all-null-values-in-a-list-and-all-sublists)? – rawr Dec 03 '15 at 01:35
  • I was trying with rapply but, like lapply, I think the problem is that rapply/lapply always has a return value, namely a list, so for a list, `l <- list(1, 2)`, `l[[2]] <- NULL` is what you desire but what is returned is `l[[2]] <- list(NULL)` instead. or at least that's my takeaway – rawr Dec 03 '15 at 01:55

0 Answers0