How to access elements of nested lists in R?

R ProgrammingServer Side ProgrammingProgramming

Sometimes the lists are contained in another list but we want to access the nested list’s elements. Since these elements are part of a list then cannot be directly accessed, first we need to access the broader list and then the list that contains the element to reach the actual element.

Example

Consider the lists x1, x2, x3, x4, and x4 and the Total_List that contains these lists −

> 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)

Printing the 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"

Now to access the first element in each of x1, x2, x3, x4, and x4 we can use the following code −

> 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"

Similarly, to access the third element in each of x1, x2, x3, x4, and x4 we just need to change 1 to 3 as shown below −

> 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"
raja
Published on 10-Aug-2020 13:14:54
Advertisements