Suppose I have a list nested within a list and I have some function which only works on vectors (like str_replace from the stringr package). The function should do its work on every element which actually entails information, …
Question 1: Is there a specific solution to my problem?
Question 2: Is there a general solution?
There should be a solution using loops, but that is all but elegant and probably very slow – efficiency does play a role here.
Let’s have an example:
# let's start easy:
test1 <- list(c("a","d"),c("b","d"),c("c","d"))
# does not work:
str_replace(test1,"d","changed")
# but this does:
lapply(test1,str_replace,"d","changed")
# but what now ?
test2 <- list(c(list("a"),"d"),c("b","d"),c("c","d"))
# does not work! :-(
lapply(test2,str_replace,"d","changed")
You can use
unlist/relist:I believe this is pretty efficient, but have not tested.