Introduction

This lab has two goals:

  • Create simple linear regression models from data.
  • Use model output to interpret coefficients and assess evidence for a linear association.

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.

Simple linear regression

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

Fitting a model with lm()

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.

  • Estimate: The intercept and slope estimates give the fitted equation. Here, \(\hat y = 29.60 - 0.0412(\text{disp})\).
  • Std. Error: This describes uncertainty in the estimated coefficient, not the spread of individual vehicles around the line.
  • t value: For the slope, this is \(\hat\beta_1/SE(\hat\beta_1)\), testing \(H_0:\beta_1=0\).
  • Pr(>|t|): The two-sided p-value for that test.

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.

Plotting the fitted line

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.

Practice

Question 1: Vehicle weight

Investigate the relationship between vehicle weight and fuel economy, using fuel economy as the outcome.

  • Part A: Create a scatter plot and add the fitted regression line using geom_smooth(method = lm, se = FALSE). Label the axes with their units. Describe the direction of the relationship.
  • Part B: Fit the corresponding simple linear regression model. Save it as weight_fit, then use summary() to display its output.
  • Part C: Write the fitted equation. Interpret the slope in context, remembering that wt is measured in thousands of pounds.
  • Part D: State the population null hypothesis for the slope. At \(\alpha=.05\), what do you conclude about a linear association? Justify your answer with model output
  • Part E: Use your equation to predict mean fuel economy for vehicles weighing 2,500 and 3,500 pounds. How does the difference between your predictions relate to the slope? If we had two cars with exactly the same weight, should we expect them both to have exactly the predicted fuel economy? Why or why not?

Question 2: Horsepower

Now investigate whether horsepower is linearly associated with fuel economy. Continue to use fuel economy as the outcome.

  • Part A: Create a scatter plot with a fitted line. Fit the corresponding model, save it as horsepower_fit, and display its summary. Keep weight_fit available for the final question.
  • Part B: Interpret the horsepower slope in context. Use its p-value to assess \(H_0:\beta_1=0\) at \(\alpha=.05\).
  • Part C: There are 32 observations, giving \(df=32-2=30\). Using a 95% critical value of approximately 2.04, construct a confidence interval for the horsepower slope:

\[ \hat\beta_1 \pm 2.04\,SE(\hat\beta_1). \]

Interpret your interval in context. Does it agree with your hypothesis-test conclusion?

  • Part D: The slope for horsepower is much closer to zero than the slope for weight. Does this alone mean that horsepower has a weaker association with fuel economy? Explain how the units of the two predictors affect this comparison.

Extracting and plotting residuals

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)")

Question 3: Residuals from the weight model

  • Part A: Run the code above to extract and plot the residuals from weight_fit. Include the plot in your document.
  • Part B: The first vehicle has 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.
  • Part C: Did the model overpredict or underpredict fuel economy for this vehicle? Explain using the sign of its residual.

We will use plots like this to investigate model assumptions. For this question, focus on obtaining the residuals, plotting them, and understanding their signs.