Lecture 04
R has three subsetting operators ([, [[, and $). The behavior of these operators depends on the object (class) they are being used with.
In general there are 6 different types of subsetting that can be performed:
Positive integer
Negative integer
Logical value
Empty / NULL
Zero valued
Character value (names)
Returns elements at the given location(s)
Excludes elements at the given location(s)
Returns elements that correspond to TRUE in the logical vector. Length of the logical vector is coerced to be the same as the vector being subsetted.
Returns the original vector, this is not the same as subsetting with NULL
Returns an empty vector (of the same type), this is the same as subsetting with NULL
If the vector has names, selects elements whose names correspond to the values in the name vector.
This final type of subsetting follows the rules for length coercion with a 0-length vector (i.e. the vector being subset gets coerced to having length 0 if the subsetting vector has length 0)
Subsets can also be used with assignment to update specific values within an object (in-place).
[[ and $[[ subsets like [ except it can only subset for a single value
Subsets a single value, but returns the value - not a list containing that value. Multiple values are interpreted as nested subsetting.
$ is equivalent to [[ but it only works for name based subsetting of lists (it also uses partial matching for names)
Why does the following code not work?
The expression x$y gets interpreted as x[["y"]] by R, note the inclusion of the "s, this is not the same as the expression x[[y]].
Sta 523 - Fall 2025