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
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
car_namefor the first three cars:
> auto[1:3, 8:9] > auto[1:3, c(8,9)]
- Index by name. Get
car_namefor the first three ...