R Linear Regression
Linear regression models how a numeric outcome changes with one or more predictors by fitting a straight line (or plane) through the data. It is one of the most used tools in statistics, and in R it takes one function: lm() ("linear model").
Fitting a line
The built-in women data set has the average heights (inches) and weights (pounds) of American women aged 30–39. Let's predict weight from height:
fit <- lm(weight ~ height, data = women)
fit
Call:
lm(formula = weight ~ height, data = women)
Coefficients:
(Intercept) height
-87.52 3.45
The formula weight ~ height reads "weight explained by height". The fitted line is
weight = -87.52 + 3.45 × height
so each extra inch of height goes with about 3.45 pounds more weight.
Looking at the fit
plot() with the same formula draws the data, and abline() adds the fitted line:
fit <- lm(weight ~ height, data = women)
plot(weight ~ height, data = women, pch = 19, col = "steelblue",
main = "Weight vs. height", xlab = "Height (in)", ylab = "Weight (lb)")
abline(fit, col = "red", lwd = 2)
round(coef(fit), 3)(Intercept) height
-87.517 3.450
The model summary
summary() reports the coefficients with their standard errors and p-values, and the R² (the share of the variation in the outcome that the model explains):
fit <- lm(mpg ~ wt, data = mtcars)
summary(fit)
Call:
lm(formula = mpg ~ wt, data = mtcars)
Residuals:
Min 1Q Median 3Q Max
-4.5432 -2.3647 -0.1252 1.4096 6.8727
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 37.2851 1.8776 19.858 < 2e-16 ***
wt -5.3445 0.5591 -9.559 1.29e-10 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 3.046 on 30 degrees of freedom
Multiple R-squared: 0.7528, Adjusted R-squared: 0.7446
F-statistic: 91.38 on 1 and 30 DF, p-value: 1.294e-10
How to read it:
- Estimate: the intercept and slope. Each extra 1000 lbs of weight lowers fuel economy by about 5.3 mpg.
- Pr(>|t|): the p-value for "this coefficient is really zero". A tiny value (here far below 0.05) means the relationship is very unlikely to be chance.
- Multiple R-squared of 0.75: weight alone explains about 75% of the variation in mpg.
You can extract the pieces programmatically:
fit <- lm(mpg ~ wt, data = mtcars)
s <- summary(fit)
round(s$r.squared, 3)
round(s$coefficients[, 1:3], 4)
signif(s$coefficients[, "Pr(>|t|)"], 3) # p-values[1] 0.753
Estimate Std. Error t value
(Intercept) 37.2851 1.8776 19.8576
wt -5.3445 0.5591 -9.5590
(Intercept) wt
8.24e-19 1.29e-10
Making predictions
predict() applies the model to new data. The new data must be a data frame with the same column names as the predictors:
fit <- lm(mpg ~ wt, data = mtcars)
new_cars <- data.frame(wt = c(2.0, 3.0, 4.5))
round(predict(fit, new_cars), 2)
round(predict(fit, new_cars, interval = "prediction"), 2) 1 2 3
26.60 21.25 13.24
fit lwr upr
1 26.60 20.13 33.06
2 21.25 14.93 27.57
3 13.24 6.75 19.72
The prediction interval gives a range in which a single new car of that weight is likely to fall.
Several predictors
Add predictors with +. Each coefficient is then the effect of that variable holding the others constant:
fit2 <- lm(mpg ~ wt + hp, data = mtcars)
round(coef(fit2), 4)
round(summary(fit2)$r.squared, 3)(Intercept) wt hp
37.2273 -3.8778 -0.0318
[1] 0.827
Adding horsepower raises R² from 0.75 to 0.83.
Checking the residuals
Residuals are the differences between the observed and the fitted values. A good model leaves residuals that look like random noise around zero:
fit <- lm(mpg ~ wt, data = mtcars)
res <- residuals(fit)
round(summary(res), 3)
plot(fitted(fit), res, pch = 19, xlab = "Fitted mpg", ylab = "Residual",
main = "Residuals vs. fitted")
abline(h = 0, lty = 2) Min. 1st Qu. Median Mean 3rd Qu. Max.
-4.543 -2.365 -0.125 0.000 1.410 6.873
plot(fit) draws four standard diagnostic charts at once.
Test yourself
In lm(y ~ x), what does the slope coefficient mean?
- The value of y when x = 0
- The expected change in y for a one-unit increase in x
- The correlation
- The p-value
What does an R² of 0.75 mean?
- 75% of predictions are correct
- The model explains 75% of the variation in the outcome
- The slope is 0.75
- The p-value is 0.25
What must newdata be for predict(fit, newdata)?
- A vector
- A data frame with the predictor columns
- A formula
- A matrix of residuals