如何在 R 中访问嵌套列表元素?


有时,列表包含在另一个列表中,但我们要访问嵌套的列表的元素。由于这些元素是某个列表的一部分,因此无法直接访问,首先我们需要访问更宽广的列表,然后访问包含该元素的列表才能获得实际元素。

示例

设想列表 x1、x2、x3、x4 和 x4,以及包含这些列表的 Total_List −

> x1<-c(list(1:5),list(6:10),list(11:15))
> x2<-c(list(letters[1:5]),list(letters[6:10], list(letters[11:15])))
> x3<-c(list(c("India","Australia"),list("Canada"),list(c("Russia","Malaysia"))))
> x4<-c(list("Europe"),list(c("Asia","America"),list(c("Africa","Antartica"))))
> x5<-c(list("Red"),list("Green"),list("Yellow"),list(c("White","Pink")))
> Total_Lists<-list(x1,x2,x3,x4,x5)

打印 Total_Lists −

> Total_Lists
[[1]]
[[1]][[1]]
[1] 1 2 3 4 5
[[1]][[2]]
[1] 6 7 8 9 10
[[1]][[3]]
[1] 11 12 13 14 15
[[2]]
[[2]][[1]]
[1] "a" "b" "c" "d" "e"
[[2]][[2]]
[1] "f" "g" "h" "i" "j"
[[2]][[3]]
[[2]][[3]][[1]]
[1] "k" "l" "m" "n" "o"
[[3]]
[[3]][[1]]
[1] "India" "Australia"
[[3]][[2]]
[[3]][[2]][[1]]
[1] "Canada"
[[3]][[3]]
[[3]][[3]][[1]]
[1] "Russia" "Malaysia"
[[4]]
[[4]][[1]]
[1] "Europe"
[[4]][[2]]
[1] "Asia" "America"
[[4]][[3]]
[[4]][[3]][[1]]
[1] "Africa" "Antartica"
[[5]]
[[5]][[1]]
[1] "Red"
[[5]][[2]]
[1] "Green"
[[5]][[3]]
[1] "Yellow"
[[5]][[4]]
[1] "White" "Pink"

现在,要访问 x1、x2、x3、x4 和 x4 中的第一个元素,我们可以使用以下代码 −

> lapply(Total_Lists,'[[',1)
[[1]]
[1] 1 2 3 4 5
[[2]]
[1] "a" "b" "c" "d" "e"
[[3]]
[1] "India" "Australia"
[[4]]
[1] "Europe"
[[5]]
[1] "Red"

类似地,要访问 x1、x2、x3、x4 和 x4 中的第三个元素,我们只需将 1 更改为 3,如下所示 −

> lapply(Total_Lists,'[[',3)
[[1]]
[1] 11 12 13 14 15
[[2]]
[[2]][[1]]
[1] "k" "l" "m" "n" "o"
[[3]]
[[3]][[1]]
[1] "Russia" "Malaysia"
[[4]]
[[4]][[1]]
[1] "Africa" "Antartica"
[[5]]
[1] "Yellow"

更新于:2020-08-10

已查看 3 千+

开启你的 职业生涯

通过完成课程获得认证

开始
广告