如何在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"