Performing linear regression

In this recipe, we discuss linear regression, arguably the most widely used technique. The stats package has the functionality for linear regression and R loads it automatically at startup.

Getting ready

If you have not already done so, download the data files for this chapter and ensure that the auto-mpg.csv file is in your R working directory. Install the caret package if you have not already done so. We want to predict mpg based on cylinders, displacement, horsepower, weight, and acceleration variables.

How to do it...

To perform linear regression, follow these steps:

  1. Load the caret package:
    > library(caret)
  2. Read the data:
    > auto <- read.csv("auto-mpg.csv")
  3. Convert the categorical variable cylinders into a factor with appropriate ...

Get R: Recipes for Analysis, Visualization and Machine Learning now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.