Note that a much more detailed overview of subsetting can be found in the Subsetting chapter of Advanced R.
There are 6 different ways to subset and 3 subsetting operators.
Positive integers
Negative integers
Logical vectors
Nothing
Zero returns a zero length vector
Character vector
Lists work in the same way as vectors. We’ll look at how the different subsetting operators [
, [[
, and $
change what you pull out of the list.
Matrices have two dimensions, each one is subset like a one-dimensional vector. Rows are first, then columns.
Matrices can be indexed with a single vector and in this case the matrix will behave like a vector.
Data frames can be indexed with a single vector like list (remember data frame columns are like a list). They can (and are more commonly) indexed with two vectors like a matrix.
[[
and $
to subset.[[
is most useful for lists because [
always returns a list and not the actual value.[[
only returns a single value so it can only be used with a single positive integer or a string.From @hadleywickham
The different operators are useful in different situations and you often find yourself using multiple operators in a single subsetting operation
Read the chapter on Subsetting from Advanced R for more details. In particular the section on simplifying versus preserving will save you many headaches in the future.