hans glick hans glick - 1 month ago 8
R Question

R : Extract elements of same index & depth level of a list

Here is a list :

# Build a toy list
x1=letters[1:3]
x2=letters[4:5]
x3=letters[1:8]
toy_list=list(list(list("ABX",x1),
list("ZHK",x2)),
list(list("CCC",x3)))

[[1]]
[[1]][[1]]
[[1]][[1]][[1]]
[1] "ABX"

[[1]][[1]][[2]]
[1] "a" "b" "c"


[[1]][[2]]
[[1]][[2]][[1]]
[1] "ZHK"

[[1]][[2]][[2]]
[1] "d" "e"



[[2]]
[[2]][[1]]
[[2]][[1]][[1]]
[1] "CCC"

[[2]][[1]][[2]]
[1] "a" "b" "c" "d" "e" "f" "g" "h"


Let's suppose I want to extract all elements, for example, in 2nd position, at a "deep level" of 3. In other way I want to extract elements of index
[[1]][[1]][[2]]
,
[[1]][[2]][[2]]
,
[[2]][[1]][[2]]
. Which means I want my output to be

[[1]]
[1] "a" "b" "c"

[[2]]
[1] "d" "e"

[[3]]
[1] "a" "b" "c" "d" "e" "f" "g" "h"


How would you do that in a generalize way?

Answer

With purrr, you can use at_depth(2, ...) where 2 indicates the depth level, and ... is an extractor (name/integer) or function. Simplifying the structure afterwards,

library(purrr)

toy_list %>% at_depth(2, 2) %>% flatten()

## [[1]]
## [1] "a" "b" "c"
## 
## [[2]]
## [1] "d" "e"
## 
## [[3]]
## [1] "a" "b" "c" "d" "e" "f" "g" "h"