Or put it differently: How can I use the [[
operator in a nested list?
You can consider this as a follow-up question on this one, when I asked how to determine the depth level of a list. I got some decent answers from @Spacedman and @flodel who both suggested recursive functions. Both solutions where quite similar and worked for me.
However I haven't figured out yet what to do with the information I get from these functions. Let's say I have a list nested at level i
and I want to get back a list that contains all i-th
level elements, like this:
myList$firstLevel$secondLevel$thirdLevel$fourthLevel
# fourthLevel contains 5 data.frames and thirdLevel has
# three elements
How can I get back all 15 data.frames from mylist
?
I am trying to use e.g.
lapply(mylist,"[[",2)
but obviously I just get the second element of all list elements at the first level.
EDIT: I found the following in the help of extract
respectivel ?"[["
but can't really wrap my head around it so far:
"[[ can be applied recursively to lists, so that if the single index i is a vector of length p, alist[[i]] is equivalent to alist[[i1]]...[[ip]] providing all but the final indexing results in a list."
EDIT: Don't want to end up nesting loops like this.
o <- list()
i=1
for (i in 1:2){
o[[i]] <- mylist[[c(i,1,1,1)]]
}