Linear Regression in R
Least squares is a fitting rule, not a guarantee of truth
A linear model finds the coefficients that minimise the sum of squared residuals, and that is the whole of what it optimises. Nothing in the procedure checks that the relationship really is linear, that the residuals are independent, or that the predictor you included is not a proxy for a confounder. Those properties belong to the data and to the design, and it is your job to verify them after the fit and, more importantly, to think about them before it.
The payoff when the checks pass is real: coefficients with clean causal-style interpretations, prediction intervals with honest width, and a compact description of a system that might otherwise need a hundred parameters. The cost when they fail is also real â a model that fits beautifully in-sample and misleads out of it.
- Estimate slopes with their standard errors, not as bare numbers.
- Diagnose with residuals before believing any p-value.
- Compare models on adjusted criteria and out-of-sample error, never on R-squared alone.
Prerequisites
- !R data frames and formula syntax
- !Descriptive statistics and correlation
What You'll Learn
- 1Fit simple and multiple linear models with lm() and interpret every column of the summary
- 2Test linearity, normality, homoscedasticity, and multicollinearity
- 3Compare nested and non-nested models with ANOVA, AIC, and adjusted R-squared
- 4Distinguish confidence intervals from prediction intervals when forecasting
What lm() estimates and what the summary reports
The model is written as a formula: the response on the left, predictors on the right, with operators that control how terms enter. + adds a main effect, * adds both main effects and their interaction, : adds only the interaction, and poly() or I() lets you express curvature without rewriting the data frame.
model <- lm(mpg ~ wt + hp + cyl, data = mtcars)
summary(model)
# Every piece of the table, extracted rather than eyeballed
coef(summary(model)) # estimate, SE, t, p
confint(model, level = 0.95) # interval for each coefficient
summary(model)$r.squared
summary(model)$adj.r.squared
sigma(model) # residual standard error
AIC(model); BIC(model)
# Interaction and curvature in one formula
lm(mpg ~ wt * hp, data = mtcars) # wt + hp + wt:hp
lm(mpg ~ poly(wt, 2, raw = TRUE), data = mtcars)
# Predictions with intervals for new observations
new_car <- data.frame(wt = 3, hp = 110, cyl = 6)
predict(model, newdata = new_car, interval = "confidence")
predict(model, newdata = new_car, interval = "prediction")
The coefficient table has four columns and each one answers a different question. The estimate is the fitted slope. The standard error measures how much that estimate would vary across repeated samples. The t statistic is the estimate divided by its standard error, so it is really a signal-to-noise ratio. The p-value is the probability of seeing a ratio that large if the true coefficient were zero â it says nothing about whether the effect is large enough to matter.
| Column | Question it answers | Common misuse |
|---|---|---|
| Estimate | how much does the response change per unit of predictor | reading it without units or scale |
| Std. Error | how stable is this estimate across samples | ignoring it entirely |
| t value | is the signal larger than the noise | treating it as effect size |
| Pr(>abs(t)) | how surprising under a zero coefficient | reporting as the whole finding |
| Multiple R-squared | how much variance the model explains in sample | comparing models with different predictors |
Standardised coefficients are worth computing when predictors are on incomparable scales, because they let you rank influence directly. lm(scale(y) ~ scale(x1) + scale(x2)) gives slopes in standard-deviation units, which answers the practical question of which lever moves the response most.
Reading a fitted relationship in context
Consider fuel consumption: heavier cars use more fuel, so a negative slope on weight is expected, and the interesting quantities are the size of the effect and how precisely it is pinned down. A slope of minus five means each additional hundredweight costs roughly five miles per gallon; whether that is worth acting on depends on the fleet you are managing.
simple <- lm(mpg ~ wt, data = mtcars)
simple_summary <- summary(simple)
simple_summary$coefficients
# Estimate Std. Error t value Pr(>|t|)
# (Intercept) 37.285 1.878 19.86 < 2e-16
# wt -5.344 0.559 -9.56 1.29e-10
# Effect for a meaningful change: 1000 lb heavier
b <- coef(simple)
b[1] + b[2] * 4.0 # predicted mpg at 4,000 lb
delta <- b[2] * 1.0 # change per 1000 lb if wt is in 1000s
# What share of the variance does weight alone explain?
simple_summary$r.squared # about 0.75
# Residual spread in mpg units
sigma(simple)
Notice the difference between a statistically clear slope and a practically large one. With enough observations almost any slope clears the significance threshold, so the honest report pairs the estimate with its interval and with a statement of the unit change that matters to the decision at hand.
Diagnostics: where models actually fail
R's four default diagnostic plots cover the failure modes that matter. The residuals-versus-fitted plot should show no pattern â a funnel means changing variance, a curve means a missing term. The normal Q-Q plot should hug the diagonal; deviations in the tails mean interval estimates are optimistic. The scale-location plot formalises the funnel check, and residuals-versus-leverage flags observations that single-handedly pull the fit.
model <- lm(mpg ~ wt + hp, data = mtcars)
par(mfrow = c(2, 2))
plot(model)
par(mfrow = c(1, 1))
# Formal checks rather than eyeballing
shapiro.test(residuals(model)) # normality of residuals
library(lmtest)
bptest(model) # Breusch-Pagan: equal variance
library(car)
vif(model) # variance inflation factors
# Influential points: who is doing the fitting?
cd <- cooks.distance(model)
hatvals <- hatvalues(model)
which(cd > 4 / nrow(mtcars)) # rule-of-thumb threshold
rstudent(model) # leave-one-out style residuals
# Reset test for functional form
library(lmtest)
resettest(model, power = 2, type = "fitted")
Multicollinearity deserves special attention because it produces coefficients that swing wildly between specifications while the model's predictions stay stable. A variance inflation factor above five means the predictor is largely explained by the others; above ten, the individual coefficient is not worth interpreting. The fix is substantive â drop or combine predictors, collect more data, or accept that you are reporting a joint effect rather than separate ones.
Linearity failures have the cheapest fix: add a squared term, a spline, or a transformation of the response. Log-transforming a right-skewed response often stabilises variance and linearises a multiplicative relationship in one move, and it changes the interpretation from additive to percentage terms.
Comparing models without fooling yourself
R-squared never decreases when you add a predictor, which makes it useless for model selection. Adjusted R-squared penalises for parameter count, AIC and BIC penalise more or less aggressively, and a nested F-test asks whether the extra terms explain enough residual variation to justify themselves.
m1 <- lm(mpg ~ wt, data = mtcars)
m2 <- lm(mpg ~ wt + hp, data = mtcars)
m3 <- lm(mpg ~ wt + hp + cyl, data = mtcars)
anova(m1, m2, m3) # nested comparison
AIC(m1, m2, m3)
BIC(m1, m2, m3)
sapply(list(m1, m2, m3), function(m) summary(m)$adj.r.squared)
# Automated search, with trace off to keep the console readable
full <- lm(mpg ~ ., data = mtcars)
best <- step(full, direction = "both", trace = 0)
coef(best)
# Cross-validated error instead of in-sample fit
set.seed(42)
folds <- sample(rep(1:5, length.out = nrow(mtcars)))
cv_rmse <- sapply(1:5, function(k) {
fit <- lm(mpg ~ wt + hp, data = mtcars[folds != k, ])
pred <- predict(fit, newdata = mtcars[folds == k, ])
sqrt(mean((mtcars$mpg[folds == k] - pred)^2))
})
mean(cv_rmse)
Stepwise selection is a convenience, not a search strategy: it conditions on a single path through the candidate space, understates the uncertainty of the chosen model, and inflates the significance of retained predictors. Use it to generate candidates, then evaluate those candidates with cross-validation or information criteria computed on the same data. For a small set of theory-driven alternatives, the explicit anova() comparison beats any automated search.
Confidence intervals and prediction intervals
The confidence interval surrounds the mean response at a given predictor value and narrows as data accumulate around that value. The prediction interval surrounds a single future observation and retains the residual variance, so it never collapses no matter how much data you collect. Reporting the wrong one is the most common forecasting error in applied work.
model <- lm(mpg ~ wt, data = mtcars)
# Grid of weights across the observed range
grid <- data.frame(wt = seq(min(mtcars$wt), max(mtcars$wt), length.out = 50))
ci <- predict(model, newdata = grid, interval = "confidence")
pi_ <- predict(model, newdata = grid, interval = "prediction")
mean(ci[,"upr"] - ci[,"lwr"]) # average confidence width
mean(pi_[,"upr"] - pi_[,"lwr"]) # always wider
# Extrapolation warning: how far outside the training range is this?
new <- data.frame(wt = 5.5)
range(mtcars$wt)
predict(model, newdata = new, interval = "prediction")
Extrapolation is the third trap. Predicting weight values outside the observed range asks the line to continue where there is no evidence it does, and with a quadratic or interaction term the fitted surface can bend violently. Check the training range before issuing any prediction, and refuse the request when the new point falls outside it.
A compact end-to-end workflow
library(broom)
fit_and_check <- function(formula, data) {
m <- lm(formula, data = data)
list(
coefficients = tidy(m, conf.int = 0.95),
fit = glance(m),
vif = if (length(attr(terms(m), "term.labels")) > 1) car::vif(m) else NA,
normality = shapiro.test(residuals(m))$p.value,
breusch_pagan = lmtest::bptest(m)$p.value,
influential = sum(cooks.distance(m) > 4 / nrow(data))
)
}
report <- fit_and_check(mpg ~ wt + hp + factor(cyl), data = mtcars)
report$coefficients
report$fit[, c("r.squared", "adj.r.squared", "AIC", "sigma")]
report$normality
report$influential
Wrapping fit and diagnostics in one function means every model in the project gets the same checks, and the returned objects drop straight into a report or a test.
Mistakes that turn fits into fiction
Common Mistakes
Selecting a model by the highest R-squared
Fix: Use adjusted R-squared, AIC, BIC, or cross-validated error, all of which penalise added parameters.
Interpreting a coefficient as an effect while ignoring collinearity
Fix: Check variance inflation factors first; above five, interpret the predictor block rather than the individual slope.
Reading a significant p-value as proof of practical importance
Fix: Report the estimate with its confidence interval in units the decision actually uses.
Fitting a straight line to clearly curved residuals
Fix: Add a polynomial or spline term, or transform the response, and re-run the residual plots.
Quoting a confidence interval where a prediction interval belongs
Fix: Prediction intervals include residual variance and are the correct band for a single future value.
Trusting stepwise selection as if it were a principled search
Fix: Treat it as candidate generation and validate the shortlist with cross-validation or theory.
Extrapolating beyond the observed range of the predictors
Fix: Check range(mtcars$wt)-style bounds before predicting and decline out-of-range requests.
Ignoring a single high-leverage observation
Fix: Inspect Cook's distance and refit without the point to see how much of the story it carries.
Practices that make regressions defensible
Best Practices
- State the estimand in words before fitting, then choose predictors to support it.
- Always run residual diagnostics and report the four default plots or their numerical equivalents.
- Report coefficients with confidence intervals, not as bare point estimates.
- Check variance inflation factors whenever two or more predictors could be correlated.
- Reserve a holdout set or use cross-validation whenever model choice is data-driven.
- Log-transform skewed responses when it stabilises variance and simplifies the relationship.
- Record the formula, sample size, and R version alongside every saved model object.
Key takeaways
Key Takeaways
- lm() minimises squared residuals; it does not verify linearity, normality, or independence.
- The coefficient table's four columns measure estimate, stability, signal-to-noise, and surprise â each answers a different question.
- R-squared always rises with more predictors, so it never justifies adding one.
- Residual plots catch functional-form and variance failures that p-values cannot see.
- Variance inflation above five makes individual coefficients uninterpretable even when predictions stay good.
- Confidence intervals describe the mean response; prediction intervals describe a single future observation.
- Wrap fit and diagnostics in one function so every model in a project is checked the same way.
Where to go next
- R Logistic Regression â the same machinery for binary outcomes.
- R Statistical Functions â the descriptive groundwork these models assume.
- R Machine Learning with caret â cross-validated comparison across many algorithms.