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.
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 tox[["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
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