7.1 Subsetting a list

Just as with vectors and matrices, individual elements of a list can be accessed using the [] operator. However, the single square brackets operator [] always returns an element that is of the same class as the original. In the case of lists, the operator [] will thus return a list as well.

> x <- list(3.1416,"hello world", FALSE, c(1:10))
> print(x[1])
[[1]]
[1] 3.1416
> class(x[1])
[1] "list"

While this is handy when working with lists, we might sometimes also access an element of a list in its own type, we need to use the double backet operator [[]].

> x <- list(3.1416,"hello world", FALSE, c(1:10))
> class(x[1])
[1] "list"
> class(x[[1]])
[1] "numeric"
> class(x[[2]])
[1] "character"
> class(x[[3]])
[1] "logical"
> class(x[[4]])
[1] "integer"

Elements of list might be named just as columns of a data frame. If they are named, they can also be accessed with the dollar sign operator $. That is quite practical because we don’t need to remember the order of elements in the list.

> y <- list(food=c("pizza","tacos"), price=c(14,25))
> class(y)
[1] "list"
> y$food
[1] "pizza" "tacos"
> class(y$food)
[1] "character"
> y$price
[1] 14 25
> class(y$price)
[1] "numeric"

The name can further be passed to the [[]] operator instead of a numeric index.

> y <- list(food=c("pizza","tacos"), price=c(14,25))
> y[['food']]
[1] "pizza" "tacos"
> y[['price']]
[1] 14 25

However, there are also some nice use cases for the single square bracket operator. Suppose we want to extract not one but two elements of a list, then we have to use []. For instance:

> y <- list(food=c("pizza","tacos"), price=c(14,25), available=c(TRUE,FALSE))
> y[c(1,3)]
$food
[1] "pizza" "tacos"

$available
[1]  TRUE FALSE

In the example above, a numeric vector c(1,3) is passed to the list using the single bracket operator and that gives back a list with food and available elements. Extracting multiple elements of a list is not possible with the $or [[]] operator.

A final note on these operators. Suppose you want to extract an element of a list by its name, but you want this name to be stored in a variables. This is only possible using the [[]] operator but not with the $ operator that only takes literal names.

> y <- list(food=c("pizza","tacos"))
> element <- "food"
> y$element
NULL
> y[[element]]
[1] "pizza" "tacos"