Subsetting & Indexing in R
Getting exactly the values you want out of a vector or a data frame is a skill you’ll use in every analysis. Everything below is a live R console — edit the code and press Run Code.
Watch: subsetting & indexing
Square brackets on vectors, [rows, columns] on data frames, and $/[[ ]] to pull a single column.
Download the R script · ▶ Practice in the playground — or edit and run each snippet below.
Pull elements out of a vector
Square brackets [ ] take elements by position, by a set of positions, by dropping with -, or by a logical test:
Index by name
If the elements are named, ask for them by name — far easier to read than counting positions:
Data frames: [rows, columns]
A data frame is indexed by rows and columns, separated by a comma. Leave a side blank to take all of it:
$ and [[ ]] pull one column
Both return the column as a plain vector:
Your turn
Next: Logical conditions & if/else → — the tests behind every filter.