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.