4.6 Quiz answers
Positive integers select elements at specific positions, negative integers drop elements; logical vectors keep elements at positions corresponding to
TRUE; character vectors select elements with matching names.
[selects sub-lists: it always returns a list. If you use it with a single positive integer, it returns a list of length one.
[[selects an element within a list.
$is a convenient shorthand:
x$yis equivalent to
drop = FALSEif you are subsetting a matrix, array, or data frame and you want to preserve the original dimensions. You should almost always use it when subsetting inside a function.
xis a matrix,
x <- 0will replace every element with 0, keeping the same number of rows and columns. In contrast,
x <- 0completely replaces the matrix with the value 0.
A named character vector can act as a simple lookup table:
c(x = 1, y = 2, z = 3)[c("y", "z", "x")]