Extracting a subset of a dataset
In this recipe, we discuss two ways to subset data. The first approach uses the row and column indices/names, and the other uses the subset()
function.
Getting ready
Download the files for this chapter and store the auto-mpg.csv
file in your R working directory. Read the data using the following command:
> auto <- read.csv("auto-mpg.csv", stringsAsFactors=FALSE)
The same subsetting principles apply for vectors, lists, arrays, matrices, and data frames. We illustrate with data frames.
How to do it...
The following steps extract a subset of a dataset:
- Index by position. Get
model_year
andcar_name
for the first three cars:> auto[1:3, 8:9] > auto[1:3, c(8,9)]
- Index by name. Get
model_year
andcar_name
for the first three ...
Get R: Recipes for Analysis, Visualization and Machine Learning now with O’Reilly online learning.
O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.