R:提取相同索引和元素的元素。列表的深度级别

时间:2016-10-29 19:36:53

标签: r 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"

假设我想要提取所有元素,例如,在第二个位置,在“深层”3中。另一方面,我想提取索引[[1]][[1]][[2]][[1]][[2]][[2]]的元素, [[2]][[1]][[2]]。这意味着我希望我的输出是

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

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

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

你会如何以一般化的方式做到这一点?

1 个答案:

答案 0 :(得分:2)

使用purrr,您可以使用at_depth(2, ...),其中2表示深度级别,...是提取器(名称/整数)或函数。之后简化结构,

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"