7.2 Nested elements of a list
For the case where a list contains an element with several values, we have to apply the same logic of how to get an element from a list and then subsetting that element to get the value we want. As an example, consider the case of a list containing a numeric vector. We can use the [[]]
operator on the list to access that vector, and then the []
operator to access an element of the vector.
> x <- list(seq(0.0, 1.0, length.out=11))
> x[[1]]
[1] 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0
> x[[1]][3]
[1] 0.2
This gets even more beautiful if we access lists within lists.
> x <- list(FALSE, list(list(1:5, 10:20), pi))
> x
[[1]]
[1] FALSE
[[2]]
[[2]][[1]]
[[2]][[1]][[1]]
[1] 1 2 3 4 5
[[2]][[1]][[2]]
[1] 10 11 12 13 14 15 16 17 18 19 20
[[2]][[2]]
[1] 3.141593
> x[[2]][[1]][[1]][3]
[1] 3
As this may become unreadable, R offers a short cut: the [[]]
can also be provided a vector of indexes to follow. Revisiting the above eample, we can use the sequence of indexes c(2,1,1,3)
to access the same element.