Linear Regression with R

Theory

The linear regression model

Goal. Explain a continuous response \(Y_i\) from fixed predictors \(x_{i1}, \dots, x_{ik}\).

\[ Y_i = \beta_0 + \beta_1 x_{i1} + \dots + \beta_k x_{ik} + \varepsilon_i , \qquad \mathbb{E}[\varepsilon_i] = 0,\ \ \mathbb{V}\mathrm{ar}[\varepsilon_i] = \sigma^2 \]

Core assumptions.

  • Predictors fixed. All the randomness of \(Y_i\) flows from the error \(\varepsilon_i\), so \(n\) i.i.d. responses mean \(n\) i.i.d. errors.
  • Centred, constant variance. \(\mathbb{E}[\boldsymbol{\varepsilon}] = \mathbf{0}\) and \(\mathrm{Cov}[\boldsymbol{\varepsilon}] = \sigma^2 \mathbb{I}_n\).
  • Optional. Normality \(\boldsymbol{\varepsilon} \sim \mathcal{N}(\mathbf{0}, \sigma^2 \mathbb{I}_n)\) for tests and confidence intervals.

Matrix form

Stack the model into vectors and matrices, \(\mathbf{y} = \mathbb{X}\boldsymbol{\beta} + \boldsymbol{\varepsilon}\), with the \(n \times (k+1)\) design matrix \(\mathbb{X}\).

  • Not a trap though a common one: linear means linear in the coefficients \(\boldsymbol{\beta}\), not in the predictors.

What to estimate. The coefficients \(\boldsymbol{\beta}\) and the error variance \(\sigma^2\).

How to pick them. Minimise the summed squared deviations:

\[ \mathrm{SSD}(\boldsymbol{\beta}, \sigma^2; \mathbf{y}, \mathbb{X}) := (\mathbf{y} - \mathbb{X}\boldsymbol{\beta})^\top (\mathbf{y} - \mathbb{X}\boldsymbol{\beta}) = \sum_{i=1}^n \left( y_i - (\beta_0 + \beta_1 x_{i1} + \dots + \beta_k x_{ik}) \right)^2 . \]

Categorical predictors

Question. The design matrix \(\mathbb{X}\) must be numeric; how do we enter a categorical predictor?

One-hot / dummy coding. A categorical variable with \(h\) categories becomes \(h-1\) numeric columns holding \(1/0\) indicators.

origin originJFK originLGA
EWR 0 0
JFK 1 0
LGA 0 1

R does this encoding for you automatically inside a formula.

Estimators

Coefficients (unbiased).

\[ \widehat{\boldsymbol{\beta}} := (\mathbb{X}^\top \mathbb{X})^{-1} \mathbb{X}^\top \mathbf{Y} \]

Fitted values.

\[ \widehat{\mathbf{Y}} = \mathbb{X}\widehat{\boldsymbol{\beta}} = \mathbb{H}\,\mathbf{Y} \]

Error variance (unbiased).

\[ \widehat{\sigma^2} := \frac{(\mathbf{Y} - \widehat{\mathbf{Y}})^\top (\mathbf{Y} - \widehat{\mathbf{Y}})}{n - k - 1} \]

Hat matrix & leverage

Hat matrix (a projection).

\[ \mathbb{H} = \mathbb{X}(\mathbb{X}^\top \mathbb{X})^{-1} \mathbb{X}^\top \]

Leverage. The diagonal terms satisfy \(0 \le h_{ii} \le 1\) and measure an observation’s influence:

\[ h_{ii} = \frac{\partial \widehat{Y_i}}{\partial Y_i} \]

Key fact. \(h_{ii}\) depends only on the predictor values, not on \(y_i\).

Residuals

Definition.

\[ \widehat{\boldsymbol{\varepsilon}} := \mathbf{y} - \widehat{\mathbf{y}} = (\mathbb{I}_n - \mathbb{H})\,\mathbf{y} \]

Two properties worth knowing.

\[ \mathbb{E}[\widehat{\varepsilon}_i] = 0, \qquad \mathbb{V}\mathrm{ar}[\widehat{\varepsilon}_i] = \sigma^2(1 - h_{ii}), \qquad \mathrm{Cov}(\widehat{\varepsilon}_i, \widehat{\varepsilon}_j) = -\sigma^2 h_{ij}\ (i \ne j) \]

Residuals are not constant-variance nor uncorrelated; that motivates standardized ones:

\[ r_i := \frac{\widehat{\varepsilon}_i}{\sqrt{\widehat{\sigma^2}(1 - h_{ii})}} \]

Studentized residuals

Definition. Each residual is computed from a model fit to every other point, excluding the point in question (externally studentized, deleted, jackknifed residuals).

\[ t_i := \frac{y_i - \widehat{y}_i^{(-i)}}{\sqrt{\widehat{\sigma^2}^{(-i)}(1 - h_{ii})}} = r_i \left( \frac{n-k-2}{n-k-1-r_i^2} \right)^{1/2} \]

Use. Under normality each \(t_i\) is Student \(t\); they power outlier detection, since a suspected outlier should not have helped fit the model in the first place.

Cook’s distance

Definition. A scaled sum of squared changes in fitted values when an observation is removed:

\[ D_i := \frac{\sum_{j=1}^n (\widehat{y}_j - \widehat{y}_j^{(-i)})^2}{\widehat{\sigma^2}(k+1)} = \frac{r_i^2}{k+1}\frac{h_{ii}}{1-h_{ii}} \]

What it conflates. It grows with large \(|r_i|\) (outlier) and with high \(h_{ii}\) (influence), and cannot tell the two apart.

In both cases, though, the safe default is to keep the observation in the fit.

Confidence intervals

Goal. An interval for the mean response \(\mathbf{x}_i^\top\boldsymbol{\beta}\) at an observed point \(\mathbf{x}_i\).

Point estimator. \(\mathbf{x}_i^\top\widehat{\boldsymbol{\beta}} \sim \mathcal{N}\!\left(\mathbf{x}_i^\top\boldsymbol{\beta},\ \sigma^2 \mathbf{x}_i^\top(\mathbb{X}^\top\mathbb{X})^{-1}\mathbf{x}_i\right)\), and \(\widehat{\boldsymbol{\beta}} \perp \widehat{\sigma^2}\).

Pivotal statistic.

\[ \frac{\mathbf{x}_i^\top\boldsymbol{\beta} - \mathbf{x}_i^\top\widehat{\boldsymbol{\beta}}}{\sqrt{\widehat{\sigma^2}\,\mathbf{x}_i^\top(\mathbb{X}^\top\mathbb{X})^{-1}\mathbf{x}_i}} \sim \mathcal{S}tudent(n-k-1) \]

Interval. \(\mathbf{x}_i^\top\widehat{\boldsymbol{\beta}} \pm t_{1-\frac{\alpha}{2}}(n-k-1)\sqrt{\widehat{\sigma^2}\,\mathbf{x}_i^\top(\mathbb{X}^\top\mathbb{X})^{-1}\mathbf{x}_i}\).

Read. a confidence interval is about the mean response, not a single new point.

Prediction intervals

Goal. An interval for a new, unobserved response at a new point \(\mathbf{x}_{n+1}\).

The extra uncertainty. A new point \(Y_{n+1}\) has its own noise \(\varepsilon_{n+1}\):

\[ Y_{n+1} = \mathbf{x}_{n+1}^\top\boldsymbol{\beta} + \varepsilon_{n+1}, \qquad \widehat{Y_{n+1}} = \mathbf{x}_{n+1}^\top\widehat{\boldsymbol{\beta}} \]

Pivotal statistic.

\[ \frac{Y_{n+1} - \widehat{Y_{n+1}}}{\sqrt{\widehat{\sigma^2}\left( 1 + \mathbf{x}_{n+1}^\top(\mathbb{X}^\top\mathbb{X})^{-1}\mathbf{x}_{n+1} \right)}} \sim \mathcal{S}tudent(n-k-1) \]

Interval. \(\widehat{Y_{n+1}} \pm t_{1-\frac{\alpha}{2}}(n-k-1)\sqrt{\widehat{\sigma^2}\left(1 + \mathbf{x}_{n+1}^\top(\mathbb{X}^\top\mathbb{X})^{-1}\mathbf{x}_{n+1}\right)}\).

The “\(1+\)” is the price of predicting fresh noise, so prediction intervals are strictly wider than confidence intervals.

Simple models

First step: look at the data

The most valuable habit of modeling: always plot first.

Both datasets share the same straight-line fit, yet only one will behave.

Second step: fit and tidy

Fit with lm(), and tap the results through broom:

  • broom::glance(): one row of overall model summaries;
  • broom::tidy(): one row per coefficient (estimates, tests);
  • broom::augment(): one row per observation (fitted, residuals, influence).

Third step: diagnose

R makes the algebra easy, but it will not check your assumptions for you.

# install.packages("ggfortify")
library(ggfortify)
first_model |> 
  autoplot(which = 1:6, label.size = 3, nrow = 2) + 
  theme_bw()

ggfortify::autoplot() turns the classical diagnostic plots into ggplot2.

Assumptions to check

Assumptions

  1. Linearity. relationship between \(x\) and \(y\) is linear;
  2. Normality. error terms are normally distributed;
  3. Homoscedasticity. error terms have constant variance;
  4. Independence. error terms are independent.

Problems this warns of

  1. Non-linearity of the relationships;
  2. Heteroscedasticity (non-constant variance);
  3. Influential / outlier values: large standardized residuals, and high-leverage points.

Residuals vs fitted

Check. non-linearity missed by the model. A flat cloud, no pattern, supports linearity.

Normal QQ plot

Check. normality of the residuals. Good when points track the straight dashed line.

Scale-location plot

Check. homoscedasticity. A flat, equally spread band supports constant variance.

Influential points & outliers

Check. zero-mean on residuals and potential outliers (residuals vs leverage: top/bottom corners); largest Cook’s distances flag influential points.

The other dataset

Same straight line, very different message once you look at the diagnostics.

More complex models

Model specification

Left of ~. the response, as named in the data. Right of ~. a combination of (possibly transformed) predictors.

Operator Meaning
+ / - add / remove a term
: interaction only
* main effects + interaction
%in% nesting
^ limit crossing to a given order
. all other variables

What the operators build

Assumes \(z\) added to predictors \(x\), with \(y\) the response (\(h\) categories for a categorical \(z\)).

Type of z Formula Model
Continuous y ~ x : z \(Y = \beta_0 + \beta_1 x z + \varepsilon\)
Continuous y ~ x * z \(Y = \beta_0 + \beta_1 x + \beta_2 z + \beta_3 xz + \varepsilon\)
Categorical y ~ x + z \(Y = \beta_0^{(0)} + \sum_\ell \beta_\ell^{(0)}\delta_{\{z=z_\ell\}} + \beta_1^{(1)}x + \varepsilon\)
Categorical y ~ x : z \(Y = \beta_0^{(0)} + \beta_1^{(1)}x + \sum_\ell \beta_\ell^{(1)} x\,\delta_{\{z=z_\ell\}} + \varepsilon\)
Categorical y ~ x * z both sets of terms (see + and : combined)

Core rule. * and : are about effects and interactions, not arithmetic multiplication.

The as-is operator I()

Problem. Inside a formula, * means interactions, not multiplication. To add a transformed predictor, e.g. both \(x\) and \(x^2\), either

  • precompute the column (e.g. with dplyr::mutate()), or
  • wrap the arithmetic in I() to tell lm() to evaluate it outside the formula first.
lm(y ~ x + I(x^2), data = my_data)

Effective model summaries

Two software families make summaries and effect plots easy:

# install.packages(c("jtools", "interactions", "ggeffects", "sjPlot"))
fit1 <- lm(metascore ~ imdb_rating + log(us_gross) + genre5, data = jtools::movies)
fit2 <- lm(metascore ~ imdb_rating + log(us_gross) + log(budget) + genre5, data = jtools::movies)

Tabular summary (1/2)

jtools::summ(fit1)
Observations 831 (10 missing obs. deleted)
Dependent variable metascore
Type OLS linear regression
F(6,824) 169.37
R² 0.55
Adj. R² 0.55
Est. S.E. t val. p
(Intercept) -39.96 5.92 -6.75 0.00
imdb_rating 12.80 0.49 25.89 0.00
log(us_gross) 0.47 0.31 1.52 0.13
genre5Comedy 6.32 1.06 5.95 0.00
genre5Drama 7.66 1.08 7.12 0.00
genre5Horror/Thriller -0.73 1.51 -0.48 0.63
genre5Other 5.86 3.25 1.80 0.07
Standard errors: OLS

+jtools::summ()* renders a tidy coefficient table with stars and standard errors.

Tabular summary (2/2)

jtools::export_summs(
  fit1, fit2, 
  error_format = "[{conf.low}, {conf.high}]", error_pos = "right"
)
Model 1Model 2
(Intercept)-39.96 ***[-51.58, -28.34]-16.47 *  [-31.16, -1.78]
imdb_rating12.80 ***[11.83, 13.77]12.28 ***[11.30, 13.26]
log(us_gross)0.47    [-0.14, 1.07]1.60 ***[0.86, 2.34]
genre5Comedy6.32 ***[4.24, 8.41]4.84 ***[2.70, 6.97]
genre5Drama7.66 ***[5.55, 9.77]6.71 ***[4.60, 8.83]
genre5Horror/Thriller-0.73    [-3.70, 2.24]-2.81    [-5.84, 0.23]
genre5Other5.86    [-0.52, 12.24]6.30 *  [0.01, 12.59]
log(budget)           -2.25 ***[-3.13, -1.37]
N831           831           
R20.55        0.57        
*** p < 0.001; ** p < 0.01; * p < 0.05.

Compare competing models side by side with export_summs().

Visual summary

jtools::plot_summs(fit1, fit2, inner_ci_level = .9)

A forest plot of the coefficients makes significance and effect size visible at a glance.

Effect plot: continuous predictor

fit <- lm(cty ~ displ + year + cyl + class + fl, data = mpg)
fit_poly <- lm(cty ~ poly(displ, 2) + year + cyl + class + fl, data = mpg)
jtools::effect_plot(fit, pred = displ, interval = TRUE, plot.points = TRUE)

jtools::effect_plot(fit_poly, pred = displ, interval = TRUE, partial.residuals = TRUE)

effect_plot() holds other predictors fixed and shows the response surface along displ.

Effect plot: categorical predictor

jtools::effect_plot(fit, pred = fl, interval = TRUE, partial.residuals = TRUE, jitter = .2)

Useful for reading how each level of a categorical predictor shifts the response.

Interaction plots

Handled by the interactions package:

  • sim_slopes(): Johnson-Neyman plot of simple slopes;
  • interact_plot(): two-way interaction with a continuous predictor;
  • cat_plot(): two-way interaction between categorical predictors.

Multicollinearity

(Multi-)collinearity means high correlation among the independent variables.

  • Data-based: badly designed experiments;
  • Structural: new variables built from existing ones.

First screen. correlation plots via corrr or ggcorrplot.

Variance inflation factor

The VIF quantifies how much a predictor’s variance is inflated by collinearity:

\[ \mathrm{VIF}_i = \frac{1}{1 - R_i^2} ,\qquad R_i^2\ \text{from regressing } X_i \text{ on the other predictors} \]

jtools::summ(fit, vifs = TRUE)
Observations 234
Dependent variable cty
Type OLS linear regression
F(13,220) 100.37
R² 0.86
Adj. R² 0.85
Est. S.E. t val. p VIF
(Intercept) -199.79 51.14 -3.91 0.00 NA
displ -1.02 0.29 -3.53 0.00 11.76
year 0.12 0.03 4.52 0.00 1.11
cyl -0.85 0.20 -4.26 0.00 8.69
classcompact -2.81 1.00 -2.83 0.01 3.69
classmidsize -2.95 0.97 -3.05 0.00 3.69
classminivan -5.08 1.05 -4.82 0.00 3.69
classpickup -5.89 0.92 -6.37 0.00 3.69
classsubcompact -2.63 1.01 -2.61 0.01 3.69
classsuv -5.59 0.88 -6.33 0.00 3.69
fld 5.93 1.85 3.21 0.00 1.60
fle -5.13 1.81 -2.84 0.00 1.60
flp -2.97 1.72 -1.73 0.08 1.60
flr -1.69 1.70 -0.99 0.32 1.60
Standard errors: OLS

Reading VIFs

  • \(\mathrm{VIF}_i \ge 1\) always.
  • Rules of thumb vary by field: above \(2\), or \(5\), or \(10\) (or disregard entirely).
  • High VIFs drown out small effects; but with interactions they can be benign and expected.

Model selection

Two complementary strategies:

Forward selection

Start with no variables; keep adding the predictor that improves fit most (by a criterion), until no significant improvement.

Backward elimination

Start with all variables; keep removing the predictor whose loss least degrades fit, until nothing can be dropped without significant loss.

stats::step() implements either (direction = "forward" or "backward") using AIC.

Your turn

  • Download the lab 11-Linear-Modeling-Exercises.qmd and its data from the course website.
  • Fit a model, produce its diagnostic plots, read them, and summarize with jtools.