O'Reilly logo

R Data Analysis Cookbook - Second Edition by Kuntal Ganguly

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to do it...

The following steps extract a subset of a dataset:

  1. Index by position. Get model_year and car_name for the first three cars by index position and index name:
# Index by Position> auto[1:3, 8:9] > auto[1:3, c(8,9)] # Index by Name> auto[1:3,c("model_year", "car_name")] 
  1. Retrieve all details for the cars with the highest or lowest mpg, using the following code:
> auto[auto$mpg == max(auto$mpg) | auto$mpg ==    min(auto$mpg),] 
  1. Get mpg and car_name for all the cars with mpg > 30 and cylinders == 6:
> auto[auto$mpg>30 & auto$cylinders==6, c("car_name","mpg")] 
  1. Get mpg and car_name for all the cars with mpg > 30 and cyl == 6, using partial name match for cylinders:
> auto[auto$mpg >30 & auto$cyl==6, c("car_name","mpg")] 

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required