This lab has two goals:
We will use lm() to fit a model, summary()
to examine the output, and geom_smooth(method = lm) to add
the fitted line to a ggplot. At the end, we will extract and plot the
residuals from one of our models.
Save each model with the name specified in the question so that you can return to it later.
Recall that simple linear regression uses one predictor to describe the mean of a quantitative outcome:
\[ y = \beta_0 + \beta_1 X + \epsilon. \]
This represents “a line + error.” Once we have estimated the coefficients, we can predict the mean outcome at a given value of \(X\):
\[ \hat y = \hat\beta_0 + \hat\beta_1 X. \]
Individual observations will vary around this fitted line.
For practice, we will use the mtcars dataset built into
R. There are 32 vehicles. You can use ?mtcars to see
descriptions of the variables. We will work with:
| Variable | Description |
|---|---|
mpg |
Fuel economy, in miles per gallon |
disp |
Engine displacement, in cubic inches |
wt |
Vehicle weight, in thousands of pounds |
hp |
Horsepower |
library(ggplot2)
theme_set(theme_bw())
## Create a working copy of the data
cars <- mtcars
head(cars[c("mpg", "disp", "wt", "hp")])
## mpg disp wt hp
## Mazda RX4 21.0 160 2.620 110
## Mazda RX4 Wag 21.0 160 2.875 110
## Datsun 710 22.8 108 2.320 93
## Hornet 4 Drive 21.4 258 3.215 110
## Hornet Sportabout 18.7 360 3.440 175
## Valiant 18.1 225 3.460 105
Similar to ANOVA and the two-sample t-test, lm()
(linear model) uses a formula with the
outcome on the left and the predictor on the right:
lm(outcome ~ predictor, data = dataset)
Here, we use engine displacement to predict fuel economy:
## Save the fitted model
displacement_fit <- lm(mpg ~ disp, data = cars)
## Display its summary
summary(displacement_fit)
##
## Call:
## lm(formula = mpg ~ disp, data = cars)
##
## Residuals:
## Min 1Q Median 3Q Max
## -4.892 -2.202 -0.963 1.627 7.231
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 29.59985 1.22972 24.07 < 0.0000000000000002 ***
## disp -0.04122 0.00471 -8.75 0.00000000094 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 3.25 on 30 degrees of freedom
## Multiple R-squared: 0.718, Adjusted R-squared: 0.709
## F-statistic: 76.5 on 1 and 30 DF, p-value: 0.000000000938
displacement_fit stores the fitted model.
summary() displays information about that model; it does
not fit a different one. For now, focus on the coefficient
table, rather than the model summaries beneath it.
The slope estimates that a one-cubic-inch increase in engine displacement is associated with a decrease of about 0.041 mpg in mean fuel economy. The small p-value provides evidence against the null hypothesis of no linear association.
We can add a regression line to a scatter plot using
geom_smooth(method = lm):
ggplot(cars, aes(x = disp, y = mpg)) +
geom_point() +
geom_smooth(method = lm, se = FALSE) +
labs(x = "Engine displacement (cubic inches)",
y = "Fuel economy (mpg)")
method = lm fits the line using the variables mapped to
the axes. se = FALSE hides the confidence band around the
fitted mean. This line matches our model because we used the same data,
outcome, and predictor.
Investigate the relationship between vehicle weight and fuel economy, using fuel economy as the outcome.
geom_smooth(method = lm, se = FALSE).
Label the axes with their units. Describe the direction of the
relationship.weight_fit, then use
summary() to display its output.wt is measured in
thousands of pounds.Now investigate whether horsepower is linearly associated with fuel economy. Continue to use fuel economy as the outcome.
horsepower_fit, and
display its summary. Keep weight_fit available for the
final question.\[ \hat\beta_1 \pm 2.04\,SE(\hat\beta_1). \]
Interpret your interval in context. Does it agree with your hypothesis-test conclusion?
A residual is an observation’s outcome minus its fitted prediction:
\[ e_i = y_i - \hat y_i. \]
A positive residual means that the observed outcome is above the
prediction; a negative residual means it is below the prediction. The
residuals() function returns these values from a saved
model.
After completing Question 1, the following code adds residuals from
the model weight_fit to cars.
## Save the residuals as a column in our working dataset
cars$weight_residual <- residuals(weight_fit)
## View the observed outcomes, predictor, and residuals
head(cars[c("mpg", "wt", "weight_residual")])
## Plot residuals against the predictor from the model
ggplot(cars, aes(x = wt, y = weight_residual)) +
geom_point() +
geom_hline(yintercept = 0, linetype = "dashed") +
labs(x = "Vehicle weight (1,000 pounds)",
y = "Residual fuel economy (mpg)")
weight_fit. Include the plot in your
document.wt = 2.62 and observed fuel economy of 21 mpg. Use the
fitted equation from Question 1 to calculate its predicted fuel economy
and residual. Check that this matches the first value in
cars$weight_residual, allowing for rounding.We will use plots like this to investigate model assumptions. For this question, focus on obtaining the residuals, plotting them, and understanding their signs.