Lists in R are a powerful data structure that can be used to store a variety of data types. They can be subsetted using the [, [[, and $ operators.
The [ operator is the most general-purpose operator. It can be used to extract single elements, multiple elements, or ranges of elements from a list. For example, the following code would extract the first element of the list x:
x <- list(foo = 1:4, bar = 0.6)
x[1]
The following code would extract the first two elements of the list x:
x[1:2]
The following code would extract the elements of the list x that are greater than 3:
x[x > 3]
The [ operator can also be used to extract elements of a list by name. For example, the following code would extract the element named "bar" from the list x:
x["bar"]
The [[ operator is used to extract single elements from a list. It can only be used to extract a single element, and the class of the returned object will not necessarily be a list. For example, the following code would extract the first element of the list x:
x[[1]]
The [[ operator can also use named indices so that you don’t have to remember the exact ordering of every element of the list. You can also use the $ operator to extract elements by name.
x[["bar"]]
x$bar
Notice you don’t need the quotes when you use the $ operator.
One thing that differentiates the [[ operator from the $ is that the [[ operator can be used with computed indices. The $ operator can only be used with literal names.
For example, the following code would extract the element named "foo" from the list x:
name <- "foo"
x[[name]]
The following code would extract the element named "name", which does not exist in the list x:
x$name
The $ operator will return NULL if the element does not exist, while the [[ operator will return an error.