4.2 Selecting a single element

[[ and $ are used to extract single elements (note: a vector can be a single element)

4.2.1 [[]]

Because [[]] can return only a single item, you must use it with either a single positive integer or a single string.

x <- list(1:3, "a", 4:6)
x[[1]]
#> [1] 1 2 3

Hadley Wickham recommends using [[]] with atomic vectors whenever you want to extract a single value to reinforce the expectation that you are getting and setting individual values.

4.2.2 $

  • x$y is equivalent to x[["y"]]

the $ operator doesn’t work with stored vals

var <- "cyl"

# Doesn't work - mtcars$var translated to mtcars[["var"]]
mtcars$var
#> NULL

# Instead use [[
mtcars[[var]]
#>  [1] 6 6 4 6 8 6 8 4 4 6 6 8 8 8 8 8 8 4 4 4 4 8 8 8 8 4 4 4 8 6 8 4

$ allows partial matching, [[]] does not

x <- list(abc = 1)
x$a
#> [1] 1

x[["a"]]
#> NULL

Hadley advises to change Global settings:

options(warnPartialMatchDollar = TRUE)
x$a
#> Warning in x$a: partial match of 'a' to 'abc'
#> [1] 1

tibbles don’t have this behavior

penguins$s
#> Warning: Unknown or uninitialised column: `s`.
#> NULL

4.2.3 missing and out of bound indices

  • Due to the inconsistency of how R handles such indices, purrr::pluck() and purrr::chuck() are recommended
x <- list(
  a = list(1, 2, 3),
  b = list(3, 4, 5)
)
purrr::pluck(x, "a", 1)
# [1] 1
purrr::pluck(x, "c", 1)
# NULL
purrr::pluck(x, "c", 1, .default = NA)
# [1] NA

4.2.4 @ and slot()

  • @ is $ for S4 objects (to be revisited in Chapter 15)

  • slot() is [[ ]] for S4 objects