A list can be subset with [
:
l1 <- list(c(1, 2, 3), 'two' = c("a", "b", "c"), list(10, 20))
l1
## [[1]]
## [1] 1 2 3
##
## $two
## [1] "a" "b" "c"
##
## [[3]]
## [[3]][[1]]
## [1] 10
##
## [[3]][[2]]
## [1] 20
l1[1]
## [[1]]
## [1] 1 2 3
l1['two']
## $two
## [1] "a" "b" "c"
l1[[2]]
## [1] "a" "b" "c"
l1[['two']]
## [1] "a" "b" "c"
Note the result of l1[2]
is still a list, as the [
operator selects elements of a list, returning a smaller list. The [[
operator extracts list elements, returning an object of the type of the list element.
Elements can be indexed by number or a character string of the name (if it exists). Multiple elements can be selected with [
by passing a vector of numbers or strings of names. Indexing with a vector of length > 1
in [
and [[
returns a "list" with the specified elements and a recursive subset (if available), respectively:
l1[c(3, 1)]
## [[1]]
## [[1]][[1]]
## [1] 10
##
## [[1]][[2]]
## [1] 20
##
##
## [[2]]
## [1] 1 2 3
Compared to:
l1[[c(3, 1)]]
## [1] 10
which is equivalent to:
l1[[3]][[1]]
## [1] 10
The $
operator allows you to select list elements solely by name, but unlike [
and [[
, does not require quotes. As an infix operator, $
can only take a single name:
l1$two
## [1] "a" "b" "c"
Also, the $
operator allows for partial matching by default:
l1$t
## [1] "a" "b" "c"
in contrast with [[
where it needs to be specified whether partial matching is allowed:
l1[["t"]]
## NULL
l1[["t", exact = FALSE]]
## [1] "a" "b" "c"
Setting options(warnPartialMatchDollar = TRUE)
, a "warning" is given when partial matching happens with $
:
l1$t
## [1] "a" "b" "c"
## Warning message:
## In l1$t : partial match of 't' to 'two'