- Simple linear regression looks at how one variable is related to another.
- It uses a straight line to help explain the relationship.
- We can also use the line to make predictions.
Our question: Do heavier cars tend to get fewer miles per gallon?
Our question: Do heavier cars tend to get fewer miles per gallon?
mtcars, a dataset that comes with R.wt is the car’s weight in 1,000 pounds.mpg is its fuel efficiency in miles per gallon.## wt mpg ## Mazda RX4 2.620 21.0 ## Mazda RX4 Wag 2.875 21.0 ## Datsun 710 2.320 22.8 ## Hornet 4 Drive 3.215 21.4 ## Hornet Sportabout 3.440 18.7
This scatterplot shows weight and miles per gallon for each car.
We describe a straight-line relationship with:
\[\hat{y} = b_0 + b_1x\]
We use lm() in R to fit the regression line.
For our data, the fitted line is approximately:
\[\widehat{mpg} = 37.29 - 5.34(wt)\]
The line shows the overall trend, not a perfect prediction for every car.
Move your mouse over the dots to explore individual cars.
Let’s predict the fuel efficiency of a car weighing 3,000 pounds.
Since weight is measured in thousands of pounds, \(x = 3\).
\[\widehat{mpg} = b_0 + b_1(3)\]
\[\widehat{mpg} = 37.29 - 5.34(3) \approx 21.25\]
So our model predicts about 21.3 MPG for that car.
This is the main code used to fit the line and make a prediction.
# Use the built-in mtcars dataset fit <- lm(mpg ~ wt, data = mtcars) # See the regression results summary(fit) # Predict MPG for a 3,000-pound car predict(fit, newdata = data.frame(wt = 3))
Data source: R’s built-in mtcars dataset.