How can I bind to a subitem of a list in a list

Suppose I have a list nested in a list and I have a function that only works with vectors (for example, str_replace from the stringr package). A function should do its job on every element that 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's all, but elegant and probably very slow - efficiency plays a role here.

Let has an example :

# let 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") 
+4
source share
3 answers

You can use unlist / relist :

 library(stringr) test <- list(c(list("a"),"d"),c("b","d"),c("c","d")) test2 <- unlist(test) test2 <- str_replace(test2,"d","changed") relist(test2,test) [[1]] [[1]][[1]] [1] "a" [[1]][[2]] [1] "changed" [[2]] [1] "b" "changed" [[3]] [1] "c" "changed" 

I believe this is quite effective, but not tested.

+3
source

Here's how to use rapple for this. Pay attention to the position ... in the rapply definition - this happens after dflt and how . For this reason, we call str_replace arguments:

 rapply(test,str_replace,pattern="d",replacement="changed",how='replace') [[1]] [[1]][[1]] [1] "a" [[1]][[2]] [1] "changed" [[2]] [1] "b" "changed" [[3]] [1] "c" "changed" 
+5
source

rapply recursively applies a function to each item in the list. You may need to experiment with the how parameter to get the correct output, but it should give you what you need.

rapply documentation here .

+2
source

All Articles