Skip to main content

6. Multiple linear regression

Packages

library(MuMIn)   # exhaustive model selection
library(ggplot2) # data visualization
library(effects) # extract model effects
library(car)     # variance inflation factor
library(dplyr)   # data manipulation
theme_set(theme_light())

Data

We continue with the airquality data from previous sessions: daily measurements of ozone concentration, solar radiation, wind speed and temperature in New York from May to September 1973. In this lab, we model ozone as a function of several of these variables at once.

# load airquality dataset
airq <- read.table("data/airquality.txt", sep = ",", dec = ".", header = TRUE)

# remove observations with missing data
airq <- na.omit(airq)

# log-transform Ozone
airq$logOzone <- log(airq$Ozone)

# convert the numeric Month column into a factor variable
airq$Month <- factor(airq$Month, levels = 5:9,
                                 labels = c("May", "Jun", "Jul", "Aug", "Sep"))

# print first rows of the dataset on screen
head(airq)
  Doy Ozone Solar Wind Temp Month Day logOzone
1 121    41   190  7.4   67   May   1 3.713572
2 122    36   118  8.0   72   May   2 3.583519
3 123    12   149 12.6   74   May   3 2.484907
4 124    18   313 11.5   62   May   4 2.890372
7 127    23   299  8.6   65   May   7 3.135494
8 128    19    99 13.8   59   May   8 2.944439
# colors for the months, used in all plots below
month_cols <- c(May = "#E41A1C", Jun = "#377EB8", Jul = "#4DAF4A",
                Aug = "#984EA3", Sep = "#FF7F00")

Exploratory analysis

Before fitting a multiple regression model, we explore the data to answer two questions. First, how is the response related to each predictor, and do we need to transform variables? Second, how are the predictors related to each other, and are some strongly correlated (collinear)? The separate effects of correlated predictors are hard to estimate, so their coefficients are less precise and harder to interpret. This matters less when the goal is prediction.

The cor() function computes the correlations between all variables of a data frame. With the method argument, you can choose between the “pearson” (default), “kendall” and “spearman” correlation coefficients. Pearson measures linear association, whereas Kendall and Spearman are based on ranks and measure monotonic association, so they also capture relationships that are monotonic but not linear.

cor(airq[, c("Ozone", "logOzone", "Solar", "Wind", "Temp")])
              Ozone   logOzone      Solar       Wind       Temp
Ozone     1.0000000  0.8923132  0.3483417 -0.6124966  0.6985414
logOzone  0.8923132  1.0000000  0.4561082 -0.5557003  0.7448232
Solar     0.3483417  0.4561082  1.0000000 -0.1271835  0.2940876
Wind     -0.6124966 -0.5557003 -0.1271835  1.0000000 -0.4971897
Temp      0.6985414  0.7448232  0.2940876 -0.4971897  1.0000000

The function pairs() draws scatterplots for all pairs of variables. The GGally package provides a more elaborate version with ggpairs().

pairs(airq[, c("Ozone", "logOzone", "Solar", "Wind", "Temp")])

Ozone increases with temperature (r = 0.70) and decreases with wind speed (r = -0.61), while its relationship with solar radiation is weaker (r = 0.35). The relationships with temperature and wind are curved, and the spread of ozone increases with its level, which is why we use log-transformed ozone as the response. With logOzone, the relationships are closer to linear, and the correlations with temperature (r = 0.74) and solar radiation (r = 0.46) are stronger. The correlation with wind speed becomes slightly weaker (r = -0.56), because the log transformation compresses the high ozone values, which occur mostly on calm days. Among the predictors, temperature and wind are moderately correlated (r = -0.50), and the other correlations are weak. Collinearity is therefore unlikely to be a problem, but we check it with the variance inflation factor below to be safe.

Multiple regression formula

A multiple regression model is specified with a formula in which the predictors are separated by +. The + means that the predictors have an additive effect on the response: the effect of each predictor is the same, whatever the values of the other predictors. The intercept is included automatically. It can be written explicitly as logOzone ~ 1 + Temp + Solar + Wind, and it can be omitted with logOzone ~ 0 + Temp + Solar + Wind, which forces the regression through the origin.

lm1 <- lm(logOzone ~ Temp + Solar + Wind, data = airq)
summary(lm1)

Call:
lm(formula = logOzone ~ Temp + Solar + Wind, data = airq)

Residuals:
     Min       1Q   Median       3Q      Max 
-2.06193 -0.29970 -0.00231  0.30756  1.23578 

Coefficients:
              Estimate Std. Error t value Pr(>|t|)    
(Intercept) -0.2621323  0.5535669  -0.474 0.636798    
Temp         0.0491711  0.0060875   8.077 1.07e-12 ***
Solar        0.0025152  0.0005567   4.518 1.62e-05 ***
Wind        -0.0615625  0.0157130  -3.918 0.000158 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.5086 on 107 degrees of freedom
Multiple R-squared:  0.6644,    Adjusted R-squared:  0.655 
F-statistic: 70.62 on 3 and 107 DF,  p-value: < 2.2e-16

Transformed terms, such as polynomials, can be added directly in the formula with the I() function. Inside a formula, operators like +, -, * and ^ have a special meaning. I() makes R evaluate them as arithmetic instead, so I(Solar^2) adds the square of solar radiation as a predictor:

lm2 <- lm(logOzone ~ Temp + Solar + I(Solar^2) + Wind, data = airq)
summary(lm2)

Call:
lm(formula = logOzone ~ Temp + Solar + I(Solar^2) + Wind, data = airq)

Residuals:
    Min      1Q  Median      3Q     Max 
-1.9005 -0.2702  0.0025  0.3128  1.1195 

Coefficients:
              Estimate Std. Error t value Pr(>|t|)    
(Intercept) -2.369e-01  5.458e-01  -0.434 0.665200    
Temp         4.492e-02  6.355e-03   7.068 1.74e-10 ***
Solar        7.259e-03  2.399e-03   3.026 0.003113 ** 
I(Solar^2)  -1.413e-05  6.957e-06  -2.031 0.044735 *  
Wind        -5.876e-02  1.555e-02  -3.779 0.000261 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.5013 on 106 degrees of freedom
Multiple R-squared:  0.677, Adjusted R-squared:  0.6648 
F-statistic: 55.54 on 4 and 106 DF,  p-value: < 2.2e-16

The update() function adds or removes terms from an existing model. In the formula, . stands for the terms of the original model, so . ~ . + I(Temp^2) keeps the response and all predictors of lm2 and adds the squared temperature:

# add a term to model lm2
lm3 <- update(lm2, . ~ . + I(Temp^2))
summary(lm3)

Call:
lm(formula = logOzone ~ Temp + Solar + I(Solar^2) + Wind + I(Temp^2), 
    data = airq)

Residuals:
    Min      1Q  Median      3Q     Max 
-2.0348 -0.3120 -0.0096  0.3105  1.0568 

Coefficients:
              Estimate Std. Error t value Pr(>|t|)    
(Intercept)  3.932e+00  2.743e+00   1.433  0.15471    
Temp        -6.687e-02  7.238e-02  -0.924  0.35768    
Solar        7.649e-03  2.397e-03   3.192  0.00187 ** 
I(Solar^2)  -1.508e-05  6.938e-06  -2.173  0.03203 *  
Wind        -5.635e-02  1.553e-02  -3.630  0.00044 ***
I(Temp^2)    7.280e-04  4.696e-04   1.550  0.12407    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.498 on 105 degrees of freedom
Multiple R-squared:  0.6842,    Adjusted R-squared:  0.6692 
F-statistic:  45.5 on 5 and 105 DF,  p-value: < 2.2e-16
# remove a term from model lm3
lm4 <- update(lm3, . ~ . - Wind)
summary(lm4)

Call:
lm(formula = logOzone ~ Temp + Solar + I(Solar^2) + I(Temp^2), 
    data = airq)

Residuals:
     Min       1Q   Median       3Q      Max 
-1.84009 -0.34667 -0.02282  0.29117  1.39926 

Coefficients:
              Estimate Std. Error t value Pr(>|t|)   
(Intercept)  3.561e+00  2.895e+00   1.230  0.22140   
Temp        -8.328e-02  7.628e-02  -1.092  0.27737   
Solar        8.439e-03  2.520e-03   3.349  0.00112 **
I(Solar^2)  -1.751e-05  7.291e-06  -2.402  0.01805 * 
I(Temp^2)    8.983e-04  4.933e-04   1.821  0.07145 . 
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.5258 on 106 degrees of freedom
Multiple R-squared:  0.6446,    Adjusted R-squared:  0.6312 
F-statistic: 48.06 on 4 and 106 DF,  p-value: < 2.2e-16

Variance inflation

Collinearity makes coefficient estimates less precise, which shows up as larger standard errors. The variance inflation factor (VIF) measures this for each predictor \(j\) as \(\text{VIF}_j = 1 / (1 - R^2_j)\), where \(R^2_j\) is the \(R^2\) of a regression of predictor \(j\) on all other predictors. A VIF of 1 means that the predictor is uncorrelated with the others. A VIF of 4 means that the variance of its coefficient is four times as large as without collinearity, so its standard error is twice as large. Values above 5 or 10 are commonly taken as a sign of problematic collinearity (Zuur et al., 2007, p. 469). The function vif() from the car package computes the VIF for each term of a model:

vif(lm1)
    Temp    Solar     Wind 
1.431367 1.095253 1.329070 
vif(lm2)
      Temp      Solar I(Solar^2)       Wind 
  1.605699  20.932082  19.854186   1.339629 
vif(lm3)
      Temp      Solar I(Solar^2)       Wind  I(Temp^2) 
211.036259  21.165558  20.008742   1.353133 210.162439 

In lm1, all VIFs are below 1.5, so temperature, solar radiation and wind are not correlated strongly enough to inflate the standard errors much. In lm2 and lm3, the VIFs of the polynomial terms are much higher: about 20 for Solar and I(Solar^2), and in lm3 above 200 for Temp and I(Temp^2). A variable and its square are strongly correlated, because both increase together over the range of positive values. This collinearity is built into the model and does not affect the fitted values, but it makes the coefficients of the linear and quadratic terms hard to interpret on their own. Centering the variable before squaring it, e.g. I((Temp - mean(Temp))^2), removes most of this correlation.

Variable intercepts and indicator variables

Ozone may differ between months for reasons that temperature alone does not capture, for example seasonal differences in weather patterns or emissions. Adding Month as a predictor accounts for such differences: the model allows the mean of logOzone at a given temperature to differ between months. In the regression equation, this shifts the regression line up or down for each month, so each month has its own intercept. The slope of Temp stays the same in all months, and the model thus describes parallel regression lines, one for each month. In R, this model is fitted as:

lm5 <- lm(logOzone ~ Temp + Month, data = airq)

The formula notation is convenient, but it hides how Month enters the regression equation. Because Month is a categorical variable, it has to be coded numerically before it can enter the equation. In R, categorical predictors are stored as factors. When a factor is included in a model, R represents its categories by indicator variables, also called dummy variables, which are 1 if an observation belongs to a given level and 0 otherwise. One level serves as the reference level and gets no indicator variable of its own. With May as the reference level, the model contains four indicator variables, MonthJun to MonthSep, one for each of the other months. Writing out the model equation shows how they work and why the regression lines are parallel:

\[ \begin{aligned} \text{logOzone} = \; & \beta_0 + \beta_1 \text{Temp} + \beta_2 \text{MonthJun} + \beta_3 \text{MonthJul} \\ & + \beta_4 \text{MonthAug} + \beta_5 \text{MonthSep} + \epsilon \end{aligned} \]

Because the indicator variables are either 0 or 1, the equation simplifies for each month. For May, all indicator variables are 0:

\[ \begin{aligned} \text{logOzone} &= \beta_0 + \beta_1 \text{Temp} + \beta_2 \cdot 0 + \beta_3 \cdot 0 + \beta_4 \cdot 0 + \beta_5 \cdot 0 + \epsilon \\ &= \beta_0 + \beta_1 \text{Temp} + \epsilon \end{aligned} \]

For July, only MonthJul is 1:

\[ \begin{aligned} \text{logOzone} &= \beta_0 + \beta_1 \text{Temp} + \beta_2 \cdot 0 + \beta_3 \cdot 1 + \beta_4 \cdot 0 + \beta_5 \cdot 0 + \epsilon \\ &= \beta_0 + \beta_1 \text{Temp} + \beta_3 + \epsilon \end{aligned} \]

Since \(\beta_0\) and \(\beta_3\) are both constants, they combine into the intercept for July:

\[ \text{logOzone} = (\beta_0 + \beta_3) + \beta_1 \text{Temp} + \epsilon \]

The model assumes the same residual variance in all months. The indicator variables shift the fitted lines without changing that assumption.

Interpreting and testing the coefficients

With the indicator variables in mind, we can now look at the model output:

summary(lm5)

Call:
lm(formula = logOzone ~ Temp + Month, data = airq)

Residuals:
     Min       1Q   Median       3Q      Max 
-2.26925 -0.29321  0.03879  0.34206  1.50462 

Coefficients:
             Estimate Std. Error t value Pr(>|t|)    
(Intercept) -2.138938   0.546860  -3.911 0.000163 ***
Temp         0.074715   0.008037   9.296 2.32e-15 ***
MonthJun    -0.468759   0.243768  -1.923 0.057192 .  
MonthJul    -0.244664   0.214692  -1.140 0.257045    
MonthAug    -0.293629   0.217549  -1.350 0.180009    
MonthSep    -0.387591   0.179445  -2.160 0.033053 *  
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.5748 on 105 degrees of freedom
Multiple R-squared:  0.5793,    Adjusted R-squared:  0.5593 
F-statistic: 28.92 on 5 and 105 DF,  p-value: < 2.2e-16

The coefficients correspond to the \(\beta\)s in the model equation above. (Intercept) is \(\beta_0\), the intercept for the reference month May, and Temp is \(\beta_1\), the slope shared by all months. MonthJun to MonthSep are \(\beta_2\) to \(\beta_5\). Each of them is the difference in intercept between that month and May, i.e. how much higher or lower logOzone is in that month than in May at the same temperature. The standard errors and t-tests of these coefficients therefore also refer to the differences from May. Each t-test tests whether a month differs significantly from May. Here, only September differs significantly from May (p = 0.033), June is borderline (p = 0.057), and July and August do not differ significantly.

Whether Month as a whole improves the model is a different question. It is answered by an ANOVA, which compares the models with and without Month:

anova(lm(logOzone ~ Temp, data = airq), lm5)
Analysis of Variance Table

Model 1: logOzone ~ Temp
Model 2: logOzone ~ Temp + Month
  Res.Df    RSS Df Sum of Sq      F Pr(>F)
1    109 36.719                           
2    105 34.696  4    2.0227 1.5303 0.1987

Here, anova() compares two nested models: the simpler model lm(logOzone ~ Temp), which contains only the continuous predictor, and lm5, which also contains the categorical predictor Month. The F-test tests whether the additional terms, i.e. the four indicator variables, reduce the residual sum of squares by more than expected by chance. Its null hypothesis is that all months have the same intercept, so unlike the t-tests, its result does not depend on which month is the reference level. This is the same test as in the chapter on linear regression and in the one-way ANOVA of the soil example, where it was applied to a single model with a continuous or a categorical predictor. In that case, the simpler model was the mean model, which has only an intercept.

Note

This F-test for comparing models should not be confused with the two-sample F-test in the previous chapter, which compares the variances of two samples. Both use the F-distribution, but they test different hypotheses.

Month as a whole is not significant (p = 0.2), although September differs from May. The differences from May are all negative, between -0.47 and -0.24, but they are estimated with large standard errors, and taken together they do not explain enough additional variation.

To compare other pairs of months, we can change the reference level with relevel(), e.g. airq$Month <- relevel(airq$Month, ref = "Jul"), and refit the model. The more t-tests we run, however, the more likely it becomes that one of them is significant by chance alone, even if the months do not differ (see multiple comparisons in the previous chapter).

Calculating the intercepts

The intercept of each month follows from the model equation. For May, it is \(\beta_0\) = -2.14. For July, it is \(\beta_0 + \beta_3\) = -2.14 + (-0.24) = -2.38, and the other months work the same way. The intercepts are the predicted logOzone at a temperature of 0 °F, far outside the observed temperatures, so their values are not meaningful on their own. The differences between them, MonthJun to MonthSep, are meaningful, however: because the lines are parallel, the difference between two months is the same at every temperature. To make the intercepts themselves meaningful, we can subtract a reference temperature from Temp before fitting the model, e.g. the mean temperature with Temp - mean(Temp) (see centered predictors). The intercepts then refer to that temperature.

The plot below is drawn from the coefficients: we calculate the intercepts and the common slope and draw the lines with geom_abline(). In practice, effect() does this for us (see visualizing effects).

slope <- coef(lm5)['Temp']

intercepts <- c(coef(lm5)[1], coef(lm5)[1] + coef(lm5)[3:6])
names(intercepts) <- c("May", "Jun", "Jul", "Aug", "Sep")
intercepts
      May       Jun       Jul       Aug       Sep 
-2.138938 -2.607697 -2.383602 -2.432567 -2.526528 
ggplot(airq, aes(x = Temp, y = logOzone)) +
  geom_point(aes(col = Month)) +
  scale_color_manual(values = month_cols) +
  geom_abline(slope = slope, intercept = intercepts["May"], col = month_cols["May"]) +
  geom_abline(slope = slope, intercept = intercepts["Jun"], col = month_cols["Jun"]) +
  geom_abline(slope = slope, intercept = intercepts["Jul"], col = month_cols["Jul"]) +
  geom_abline(slope = slope, intercept = intercepts["Aug"], col = month_cols["Aug"]) +
  geom_abline(slope = slope, intercept = intercepts["Sep"], col = month_cols["Sep"])

The lines of June to September all lie below the May line, but compared to the scatter around the lines, the differences between months are small. For example, logOzone in July is 0.24 lower than in May at the same temperature. To express this difference on the original scale, we use that the difference of two logarithms is the logarithm of their ratio:

\[ \beta_3 = \log(\text{Ozone}_\text{Jul}) - \log(\text{Ozone}_\text{May}) = \log\left(\frac{\text{Ozone}_\text{Jul}}{\text{Ozone}_\text{May}}\right) \]

Taking the exponential on both sides gives the ratio. Because the temperature term is the same in both months, it cancels out, and only the intercepts remain in the fraction:

\[ e^{\beta_3} = \frac{\text{Ozone}_\text{Jul}}{\text{Ozone}_\text{May}} = \frac{e^{\beta_0 + \beta_3}}{e^{\beta_0}} = \frac{e^{-2.384}}{e^{-2.139}} = 0.78 \]

The back-transformation turns the constant difference on the log scale into a constant factor on the original scale. In general, an additive effect on the log scale corresponds to a multiplicative effect on the original scale. At the same temperature, ozone in July is 0.78 times the ozone in May, i.e. 22% lower. This factor is the same at every temperature, whereas the absolute difference in ozone grows with temperature, because ozone itself increases with temperature.

The standard errors of these intercepts cannot be calculated as easily. The standard error of the intercept for July is not the sum of the standard errors of \(\beta_0\) and \(\beta_3\), because the two estimates are correlated. Its variance is \(\text{Var}(\beta_0) + \text{Var}(\beta_3) + 2\,\text{Cov}(\beta_0, \beta_3)\), which requires the covariance matrix of the estimates (vcov(lm5)). It is easier to refit the model with July as the reference level, or to use the effects package, which calculates the standard errors for us.

To check that R uses these indicator variables, we create them by hand and fit the model again. We use May as the reference level and create one indicator variable for each of the other four months:

airq$dummyJun <- ifelse(airq$Month=="Jun", 1, 0)
airq$dummyJul <- ifelse(airq$Month=="Jul", 1, 0)
airq$dummyAug <- ifelse(airq$Month=="Aug", 1, 0)
airq$dummySep <- ifelse(airq$Month=="Sep", 1, 0)

head(airq[!duplicated(airq$Month), -1])
    Ozone Solar Wind Temp Month Day logOzone dummyJun dummyJul dummyAug dummySep
1      41   190  7.4   67   May   1 3.713572        0        0        0        0
38     29   127  9.7   82   Jun   7 3.367296        1        0        0        0
62    135   269  4.1   84   Jul   1 4.905275        0        1        0        0
93     39    83  6.9   81   Aug   1 3.663562        0        0        1        0
124    96   167  6.9   91   Sep   1 4.564348        0        0        0        1

In general, a factor with \(n\) levels needs \(n-1\) indicator variables, and each of them adds one coefficient to the model, so the number of parameters grows with the number of levels. We fit the model with the four indicator variables instead of Month and compare its coefficients with those of lm5:

lm5_manual <- lm(logOzone ~ Temp + dummyJun + dummyJul + dummyAug + dummySep,
                 data = airq)
cbind(manual = coef(lm5_manual), factor = coef(lm5))
                 manual      factor
(Intercept) -2.13893784 -2.13893784
Temp         0.07471496  0.07471496
dummyJun    -0.46875932 -0.46875932
dummyJul    -0.24466375 -0.24466375
dummyAug    -0.29362919 -0.29362919
dummySep    -0.38759055 -0.38759055

The coefficients are identical; only the names differ.

Variable slopes and interaction effects

In the model without interaction, the month changed the overall level of ozone, but temperature had the same effect in every month: one degree warmer raised ozone by the same percentage in May as in September. An interaction drops this assumption and allows the effect of temperature to depend on the month. For example, warmer days might raise ozone more strongly in one month than in another. In terms of the regression lines, the model without interaction gave each month its own intercept with a common slope. The interaction also gives each month its own slope, so the lines are no longer parallel. In the model equation, the interaction terms are the products of Temp and the indicator variables, so each of them is zero except in its month, where it changes the slope of Temp. Their coefficients are \(\beta_6\) to \(\beta_9\):

\[ \begin{aligned} \text{logOzone} = \; & \beta_0 + \beta_1 \text{Temp} \\ & + \beta_2 \text{MonthJun} + \beta_3 \text{MonthJul} + \dots + \beta_5 \text{MonthSep} \\ & + \beta_6 \, \text{Temp} \cdot \text{MonthJun} + \beta_7 \, \text{Temp} \cdot \text{MonthJul} \\ & + \dots + \beta_9 \, \text{Temp} \cdot \text{MonthSep} + \epsilon \end{aligned} \]

As in the model without interaction, the equation simplifies for each month. For May, the reference month, all indicator variables are 0, so all interaction terms are 0 as well:

\[ \text{logOzone} = \beta_0 + \beta_1 \text{Temp} + \epsilon \]

The intercept for May is \(\beta_0\) and its slope is \(\beta_1\). For July, only the indicator variable for July is 1, so the terms with \(\beta_3\) and \(\beta_7\) remain:

\[ \text{logOzone} = \beta_0 + \beta_1 \text{Temp} + \beta_3 + \beta_7 \, \text{Temp} + \epsilon \]

Grouping the constant terms and the terms with Temp gives the intercept and the slope for July:

\[ \text{logOzone} = (\beta_0 + \beta_3) + (\beta_1 + \beta_7) \, \text{Temp} + \epsilon \]

As before, \(\beta_3\) is the difference in intercept between July and May. The new coefficient \(\beta_7\) is the difference in slope: how much stronger or weaker the effect of temperature is in July than in May. The other months work the same way.

Interaction terms in R

In R model formulas, an interaction between two predictors is written with a colon, var1:var2. The interaction term is usually included together with the additive effects of both predictors:

response ~ var1 + var2 + var1:var2

The shorthand var1 * var2 includes both additive effects and their interaction, so the following formula describes the same model:

response ~ var1 * var2

We fit the model with an interaction between Temp and Month:

lm6 <- lm(logOzone ~ Temp * Month, data = airq)
summary(lm6)

Call:
lm(formula = logOzone ~ Temp * Month, data = airq)

Residuals:
     Min       1Q   Median       3Q      Max 
-2.19906 -0.26980  0.00246  0.35058  1.51166 

Coefficients:
              Estimate Std. Error t value Pr(>|t|)    
(Intercept)   -2.76430    1.19238  -2.318   0.0224 *  
Temp           0.08413    0.01786   4.711 7.89e-06 ***
MonthJun       2.42798    2.33970   1.038   0.3019    
MonthJul      -3.95983    2.45826  -1.611   0.1103    
MonthAug       0.11327    1.87091   0.061   0.9518    
MonthSep       1.13404    1.54120   0.736   0.4635    
Temp:MonthJun -0.03845    0.03123  -1.231   0.2211    
Temp:MonthJul  0.04233    0.03121   1.357   0.1779    
Temp:MonthAug -0.00680    0.02477  -0.275   0.7843    
Temp:MonthSep -0.02107    0.02187  -0.963   0.3377    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.568 on 101 degrees of freedom
Multiple R-squared:  0.6048,    Adjusted R-squared:  0.5696 
F-statistic: 17.18 on 9 and 101 DF,  p-value: < 2.2e-16

The output contains the coefficients of the model equation above: the intercept and slope for May ((Intercept) and Temp), the differences in intercept from May (MonthJun to MonthSep), and the differences in slope from May, which are the interaction terms marked with a colon (Temp:MonthJun to Temp:MonthSep).

The differences in intercept have changed considerably compared to lm5: MonthJul is -3.96 in lm6, but -0.24 in lm5. Because the lines now have different slopes, the difference between months depends on temperature, and MonthJun to MonthSep are the differences at 0 °F, far outside the data. Centering Temp gives differences at a meaningful temperature (see centered predictors).

In lm6, temperature has a clear positive effect on ozone in May (Temp = 0.084, p <0.001). None of the interaction terms is significant (p = 0.18 to 0.78), so there is no clear evidence that the effect of temperature differs between months. Whether the interaction as a whole improves the model is again tested with an F-test that compares the models with and without interaction:

anova(lm5, lm6)
Analysis of Variance Table

Model 1: logOzone ~ Temp + Month
Model 2: logOzone ~ Temp * Month
  Res.Df    RSS Df Sum of Sq      F Pr(>F)
1    105 34.696                           
2    101 32.591  4    2.1056 1.6314 0.1722

The interaction does not significantly improve the model (p = 0.17).

Calculating the slopes

For May, the reference month, the intercept is (Intercept) and the slope is Temp:

\[\text{logOzone}_{\text{May}} = -2.76 + 0.084 \, \text{Temp}\]

For July, we add the difference in intercept (MonthJul) to the intercept of May and the difference in slope (Temp:MonthJul) to the slope of May:

\[\text{logOzone}_{\text{Jul}} = (-2.76 + (-3.96)) + (0.084 + 0.042) \, \text{Temp}\]

The regression lines for May and July thus differ in both intercept and slope.

The plot below is drawn from the coefficients: we calculate the intercepts and slopes for May and July and draw the lines with geom_abline(). In practice, effect() does this for all months at once (see visualizing effects).

lm6_intercept_May <- coef(lm6)['(Intercept)']
lm6_intercept_Jul <- coef(lm6)['(Intercept)'] + coef(lm6)['MonthJul']
lm6_slope_May <- coef(lm6)['Temp']
lm6_slope_Jul <- coef(lm6)['Temp'] + coef(lm6)['Temp:MonthJul']

ggplot(airq, aes(x = Temp, y = logOzone)) +
  geom_point(aes(col = Month)) +
  scale_color_manual(values = month_cols) +
  geom_abline(slope = lm6_slope_May, intercept = lm6_intercept_May, col = month_cols["May"]) +
  geom_abline(slope = lm6_slope_Jul, intercept = lm6_intercept_Jul, col = month_cols["Jul"])

The slope for July is steeper than the slope for May. As we saw in the output of lm6, however, this difference in slope is not significant (p = 0.18), so the data do not show that temperature affects ozone more strongly in July than in May.

Visualizing effects and their uncertainty

Coefficients are hard to read once a model contains factors and interactions. A plot of the fitted relationships with their confidence bands shows how the response changes with each predictor and how precisely the model estimates this. Calculating the lines by hand, as above, becomes tedious with many levels and gives no confidence intervals. We therefore use the functions effect() and Effect() from the effects package. Both calculate fitted values, together with their confidence limits, for a range of values of one or more focal predictors, i.e. the predictors we want to plot. They differ only in how the focal predictors are specified. effect() takes a term of the model, such as "Temp:Month", and this term must appear in the model formula. Effect() takes a vector of predictor names, such as c("Temp", "Month"), in any combination, including predictors that do not interact in the model.

All other predictors of the model are held fixed: numeric predictors at their mean, and factors averaged over their levels, weighted by how often each level occurs. The argument fixed.predictors holds them at other values, e.g. fixed.predictors = list(given.values = c(Solar = 300)) in a model with solar radiation. For a factor, all its indicator variables must be set, e.g. c(MonthJun = 0, MonthJul = 1, MonthAug = 0, MonthSep = 0) for July, so it is usually easier to include the factor as a focal predictor. lm6 contains only Temp and Month, so no predictor is held fixed here.

The argument xlevels sets the values at which numeric focal predictors are evaluated; factors are always evaluated at all their levels. xlevels is a named list with one element per numeric focal predictor, e.g. list(Temp = c(60, 80), Wind = c(5, 10, 15)) for temperature and wind speed. Without xlevels, effect() uses five equally spaced values rounded to nice numbers, here 60 to 100 °F, which do not match the observed range of 57 to 97 °F. Since Temp is our only numeric focal predictor, we pass a list with one element, a grid of 100 temperatures across the observed range:

efct <- effect(term = "Temp:Month", mod = lm6,
               xlevels = list(Temp = seq(min(airq$Temp), max(airq$Temp), length.out = 100))) |>
        as.data.frame()
efct$Month <- factor(efct$Month, levels = c("May", "Jun", "Jul", "Aug", "Sep"))
head(efct)
      Temp Month      fit        se    lower    upper
1 57.00000   May 2.030813 0.2048673 1.624411 2.437215
2 57.40404   May 2.064803 0.1989612 1.670117 2.459488
3 57.80808   May 2.098793 0.1931440 1.715647 2.481939
4 58.21212   May 2.132783 0.1874240 1.760984 2.504582
5 58.61616   May 2.166773 0.1818104 1.806110 2.527435
6 59.02020   May 2.200762 0.1763133 1.851004 2.550521

The columns fit, lower and upper contain the fitted values and the lower and upper confidence limits on the log scale. By default, these are 95% confidence intervals; the argument confidence.level changes the level (see ?effect). We plot the fitted lines with their confidence bands (geom_ribbon()) on the log scale:

ggplot(airq) +
  geom_point(aes(x = Temp, y = logOzone, col = Month)) +
  geom_ribbon(data = efct, aes(x = Temp, ymin = lower, ymax = upper, fill = Month), alpha = 0.2) +
  geom_line(data = efct, aes(x = Temp, y = fit, col = Month)) +
  scale_color_manual(values = month_cols) +
  scale_fill_manual(values = month_cols)

To show the predictions on the original scale of ozone concentration, we back-transform the fitted values and confidence limits with exp(). The fine grid of temperatures matters here: on the original scale, the lines are curved, and with only a few temperature values they would look angular. Because the model was fitted to log-transformed ozone, exp(fit) gives the predicted median ozone concentration, not the mean. The mean on the original scale is higher, because the back-transformed distribution is right-skewed.

ggplot(airq) +
  geom_point(aes(x = Temp, y = Ozone, col = Month)) +
  geom_ribbon(data = efct, aes(x = Temp, ymin = exp(lower), ymax = exp(upper), fill = Month), alpha = 0.2) +
  geom_line(data = efct, aes(x = Temp, y = exp(fit), col = Month)) +
  scale_color_manual(values = month_cols) +
  scale_fill_manual(values = month_cols)

Continuous additive effects

In the section on variable intercepts, we covered additive effects with a categorical second predictor. Here, we look at additive effects of continuous predictors, using temperature and wind speed as an example. The additive idea stays the same: the effect of temperature on ozone is the same at every wind speed. In lm5, Month shifted the regression line of temperature up or down, which gave one parallel line per month. A continuous second predictor works the same way, but the line shifts gradually instead of jumping from one month to the next. With temperature and wind speed, the model equation is:

\[\text{logOzone} = \beta_0 + \beta_1 \text{Temp} + \beta_2 \text{Wind} + \epsilon\]

Grouping the terms without Temp gives

\[\text{logOzone} = (\beta_0 + \beta_2 \text{Wind}) + \beta_1 \text{Temp} + \epsilon\]

For each wind speed, this is a straight line with intercept \((\beta_0 + \beta_2 \text{Wind})\) and the same slope \(\beta_1\). The model thus describes parallel lines, one for every wind speed.

lm7 <- lm(logOzone ~ Temp + Wind, data = airq)
summary(lm7)

Call:
lm(formula = logOzone ~ Temp + Wind, data = airq)

Residuals:
     Min       1Q   Median       3Q      Max 
-2.36759 -0.25774  0.05869  0.35009  1.16747 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept) -0.38742    0.60050  -0.645 0.520189    
Temp         0.05655    0.00637   8.878 1.64e-14 ***
Wind        -0.05993    0.01706  -3.513 0.000649 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.5524 on 108 degrees of freedom
Multiple R-squared:  0.6004,    Adjusted R-squared:  0.593 
F-statistic: 81.14 on 2 and 108 DF,  p-value: < 2.2e-16

At a given wind speed, one degree warmer raises logOzone by 0.057. At a given temperature, an increase in wind speed by 1 mph changes it by -0.06.

In this additive model, the estimated effect of temperature on ozone does not depend on the value of wind speed, but it does depend on whether wind speed is in the model. The reason is that the two predictors vary together: hot days tend to be calm, and calm air lets ozone accumulate, so ozone is high on hot days partly because of the low wind speed. A simple regression on temperature alone cannot tell these two causes apart and attributes part of the wind effect to temperature. Fitting both predictors together separates their effects: the coefficient of temperature describes how ozone changes with temperature among days with the same wind speed. Each coefficient of a multiple regression therefore has to be read in the context of the other predictors in the model. A predictor can become more or less important, or gain or lose significance, when other predictors are added or removed.

Continuous interactions

Previously, the interaction allowed the effect of temperature to differ between months, so each month had its own slope. An interaction between two continuous predictors follows the same idea, but the effect of temperature now changes gradually with the second predictor instead of jumping from one group to the next. For example, wind disperses pollutants, so on windy days ozone might rise less strongly with temperature than on calm days. Instead of one slope per month, the slope of temperature then changes continuously with wind speed.

In the model equation, the interaction term is the product of the two predictors:

\[\text{logOzone} = \beta_0 + \beta_1 \text{Temp} + \beta_2 \text{Wind} + \beta_3 \, \text{Temp} \cdot \text{Wind} + \epsilon\]

Grouping the terms with and without Temp shows how the regression line of temperature depends on wind speed:

\[\text{logOzone} = (\beta_0 + \beta_2 \text{Wind}) + (\beta_1 + \beta_3 \text{Wind}) \, \text{Temp} + \epsilon\]

For each wind speed, this is a straight line with intercept \((\beta_0 + \beta_2 \text{Wind})\) and slope \((\beta_1 + \beta_3 \text{Wind})\). \(\beta_1\) is the slope of temperature at a wind speed of 0, and \(\beta_3\) is how much this slope changes per unit increase in wind speed. The interaction is symmetric: in the same way, the effect of wind changes with temperature. Which view is more useful depends on the question; here, wind modulating the effect of temperature is physically more plausible.

We fit the model with an interaction between Temp and Wind:

lm8 <- lm(logOzone ~ Temp * Wind, data = airq)
summary(lm8)

Call:
lm(formula = logOzone ~ Temp * Wind, data = airq)

Residuals:
     Min       1Q   Median       3Q      Max 
-2.31151 -0.28199  0.05219  0.34752  1.12276 

Coefficients:
             Estimate Std. Error t value Pr(>|t|)    
(Intercept) -2.380182   1.306868  -1.821   0.0714 .  
Temp         0.081641   0.015953   5.118 1.37e-06 ***
Wind         0.135132   0.115136   1.174   0.2431    
Temp:Wind   -0.002509   0.001465  -1.713   0.0896 .  
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.5475 on 107 degrees of freedom
Multiple R-squared:  0.6111,    Adjusted R-squared:  0.6002 
F-statistic: 56.04 on 3 and 107 DF,  p-value: < 2.2e-16

The coefficients correspond to the equation above:

  • (Intercept): logOzone at a wind speed of 0 and a temperature of 0 °F.
  • Temp: the slope of temperature at a wind speed of 0. One degree warmer raises logOzone by 0.082.
  • Wind: the slope of wind speed at a temperature of 0 °F. An increase in wind speed by 1 mph raises logOzone by 0.14. At realistic temperatures, however, the effect of wind is negative because of the interaction (see the centered model below).
  • Temp:Wind: the change in the slope of temperature per 1 mph increase in wind speed. The coefficient is negative (-0.0025), so the slope of temperature becomes smaller with increasing wind speed. With the slope \(\beta_1 + \beta_3 \text{Wind}\) from the equation above, the slope of temperature is 0.0816 + (-0.0025) \(\cdot\) 5 = 0.069 at a wind speed of 5 mph and 0.044 at 15 mph. On windy days, ozone thus rises less strongly with temperature than on calm days. This interaction is not significant, however (p = 0.09), so the data do not clearly show that the effect of temperature depends on wind speed.

The intercept and the coefficients of Temp and Wind describe situations far outside the data. The observed temperatures range from 57 to 97 °F, so a temperature of 0 °F never occurs, and calm conditions with a wind speed of 0 do not occur either. These coefficients are mathematically correct but extrapolations. Centering the predictors (see centered predictors below) moves the reference point into the data and makes them much easier to interpret.

To plot the fitted lines, we again use effect(). With xlevels, we choose the temperatures for the lines and the wind speeds for which lines are drawn. We choose wind speeds within the observed range of 2.3 to 20.7 mph, because lines for values outside this range would be extrapolations:

efct <- effect("Temp:Wind", mod = lm8,
               xlevels = list(Temp = seq(min(airq$Temp), max(airq$Temp), length.out = 100),
                              Wind = c(5, 10, 15, 20))) |>
        as.data.frame()

ggplot(airq) +
  geom_point(aes(x = Temp, y = Ozone, col = Wind)) +
  geom_line(data = efct, aes(x = Temp, y = exp(fit), col = Wind, group = Wind))

The lines become flatter with increasing wind speed, as described by the negative interaction term.

Centered predictors

The intercept and the coefficients of Temp and Wind refer to the point where both predictors are 0. If we subtract the mean from each predictor, this point becomes the mean temperature and the mean wind speed, which lie in the middle of the data. This is called centering. The centered predictors are the deviations from the mean, still in °F and mph.

airq$Temp_cnt <- airq$Temp - mean(airq$Temp)
airq$Wind_cnt <- airq$Wind - mean(airq$Wind)

lm8c <- lm(logOzone ~ Temp_cnt * Wind_cnt, data = airq)
summary(lm8c)

Call:
lm(formula = logOzone ~ Temp_cnt * Wind_cnt, data = airq)

Residuals:
     Min       1Q   Median       3Q      Max 
-2.31151 -0.28199  0.05219  0.34752  1.12276 

Coefficients:
                   Estimate Std. Error t value Pr(>|t|)    
(Intercept)        3.374014   0.057440  58.739  < 2e-16 ***
Temp_cnt           0.056702   0.006314   8.980 1.03e-14 ***
Wind_cnt          -0.060051   0.016912  -3.551 0.000572 ***
Temp_cnt:Wind_cnt -0.002509   0.001465  -1.713 0.089649 .  
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.5475 on 107 degrees of freedom
Multiple R-squared:  0.6111,    Adjusted R-squared:  0.6002 
F-statistic: 56.04 on 3 and 107 DF,  p-value: < 2.2e-16

The mean temperature is 77.8 °F and the mean wind speed is 9.9 mph. The coefficients now describe situations within the data:

  • (Intercept): logOzone at the mean temperature and the mean wind speed.
  • Temp_cnt: the slope of temperature at the mean wind speed. One degree warmer raises logOzone by 0.057.
  • Wind_cnt: the slope of wind speed at the mean temperature. An increase in wind speed by 1 mph lowers logOzone by 0.06. Unlike in lm8, the effect of wind is now negative, as expected.
  • Temp_cnt:Wind_cnt: unchanged from lm8 (-0.0025). Centering shifts the reference point, but the slope of temperature still changes by the same amount per 1 mph of wind speed.

Centering does not change the fit of the model: the fitted values, the residuals, \(R^2\) and the test of the interaction are the same as in lm8. Only the coefficients that depend on the reference point change, namely the intercept and the main effects of Temp and Wind. In models without interactions, centering changes only the intercept, because the slopes do not depend on the values of the other predictors.

Standardized predictors

Standardizing (z-transforming) goes one step further than centering: the centered predictors are also divided by their standard deviation. The reference point stays at the means, as in lm8c, but the coefficients now refer to an increase by one standard deviation instead of one °F or one mph. This makes the effects of predictors with different units comparable. The function scale() centers and standardizes in one step.

airq[, c("Wind_scl", "Temp_scl", "Solar_scl")] <- scale(airq[, c("Wind", "Temp", "Solar")])

lm8s <- lm(logOzone ~ Temp_scl * Wind_scl, data = airq)
summary(lm8s)

Call:
lm(formula = logOzone ~ Temp_scl * Wind_scl, data = airq)

Residuals:
     Min       1Q   Median       3Q      Max 
-2.31151 -0.28199  0.05219  0.34752  1.12276 

Coefficients:
                  Estimate Std. Error t value Pr(>|t|)    
(Intercept)        3.37401    0.05744  58.739  < 2e-16 ***
Temp_scl           0.54037    0.06017   8.980 1.03e-14 ***
Wind_scl          -0.21364    0.06017  -3.551 0.000572 ***
Temp_scl:Wind_scl -0.08507    0.04967  -1.713 0.089649 .  
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.5475 on 107 degrees of freedom
Multiple R-squared:  0.6111,    Adjusted R-squared:  0.6002 
F-statistic: 56.04 on 3 and 107 DF,  p-value: < 2.2e-16

The intercept is the same as in lm8c, and so are the t-values and p-values of all coefficients. Only the units have changed. The coefficient of Temp_scl is the coefficient from lm8c multiplied by the standard deviation of temperature (9.53 °F): 0.0567 \(\cdot\) 9.53 = 0.54. It is the increase in logOzone for one standard deviation of temperature at the mean wind speed. The coefficient of Wind_scl is rescaled in the same way, and the interaction is multiplied by both standard deviations.

The fitted lines show the same pattern as before, but the temperature axis is now in standard deviations:

efct <- effect("Temp_scl:Wind_scl", mod = lm8s,
               xlevels = list(Temp_scl = seq(min(airq$Temp_scl),
                                             max(airq$Temp_scl),
                                             length.out = 100))) |>
        as.data.frame()

ggplot(airq) +
  geom_point(aes(x = Temp_scl, y = Ozone, col = Wind_scl)) +
  geom_line(data = efct, aes(x = Temp_scl, y = exp(fit), col = Wind_scl, group = Wind_scl)) +
  labs(x = "Temperature (SD from mean)", col = "Wind (SD)")

Model selection

Selection criteria

Selection criteria compare candidate models by balancing goodness of fit against model complexity. They help identify models that explain the data well without introducing unnecessary parameters. Different criteria apply different penalties for complexity and may therefore favor different models. Common examples include the Akaike Information Criterion (AIC), the Bayesian Information Criterion (BIC), and adjusted \(R^2\). These criteria support relative model comparison but do not establish whether a model is appropriate or whether its assumptions are satisfied.

AIC

The Akaike Information Criterion (AIC) estimates how much information a model loses, balancing fit against the number of estimated parameters. Lower AIC indicates less information loss relative to the other candidate models. AIC is calculated as

\[ \text{AIC} = -2 \log(L) + 2k \]

where \(L\) is the maximized likelihood of the model and \(k\) is the number of estimated parameters, including the residual variance. The first term measures the fit and becomes smaller the better the model fits the data. The second term is a penalty that increases with the number of parameters.

AIC can also be read as an estimate of predictive performance: the penalty for the number of parameters approximates how much worse the model would predict new observations than it fits the data used for fitting (James et al., 2021, sec. 6.1.3). A lower AIC thus indicates a model that is expected to predict new data better. AIC does not show whether a model fits or predicts well in an absolute sense. How well a model predicts can be assessed directly with cross-validation, which we cover in the chapter on model accuracy. Compare AIC only for models fitted to the same response and observations. Here, all models use logOzone and the same complete-case data:

aic <- arrange(AIC(lm1, lm2, lm3, lm4, lm5, lm6, lm7, lm8), AIC)
aic$AICdelta <- round(aic$AIC - aic$AIC[1], 2)
aic
    df      AIC AICdelta
lm3  7 168.0743     0.00
lm2  6 168.5865     0.51
lm1  5 170.8251     2.75
lm4  6 179.1954    11.12
lm8  5 187.2015    19.13
lm7  4 188.2038    20.13
lm5  7 199.9223    31.85
lm6 11 200.9728    32.90

Unlike AIC, \(R^2\) is not suited for comparing models with different numbers of parameters. \(R^2\) always increases when terms are added, even if they only fit random noise, so it always favors the most complex model. The adjusted \(R^2\) corrects for this by penalizing additional parameters, but less strongly than AIC. For example, adding the interaction to lm5 increases the adjusted \(R^2\) of lm6, but makes its AIC worse. To compare all three criteria, we retrieve the models by their names (the row names of aic) with mget() and add both \(R^2\) values to the table:

models <- mget(row.names(aic))
aic$r.squared <- sapply(models, function(m) summary(m)$r.squared)
aic$adj.r.squared <- sapply(models, function(m) summary(m)$adj.r.squared)
aic$formula <- sapply(models, function(m) deparse1(formula(m)[[3]]))
print(aic, right = FALSE)
    df AIC      AICdelta r.squared adj.r.squared formula                                     
lm3  7 168.0743  0.00    0.6842246 0.6691876     Temp + Solar + I(Solar^2) + Wind + I(Temp^2)
lm2  6 168.5865  0.51    0.6769963 0.6648075     Temp + Solar + I(Solar^2) + Wind            
lm1  5 170.8251  2.75    0.6644239 0.6550153     Temp + Solar + Wind                         
lm4  6 179.1954 11.12    0.6446017 0.6311905     Temp + Solar + I(Solar^2) + I(Temp^2)       
lm8  5 187.2015 19.13    0.6110761 0.6001717     Temp * Wind                                 
lm7  4 188.2038 20.13    0.6004129 0.5930131     Temp + Wind                                 
lm5  7 199.9223 31.85    0.5792875 0.5592536     Temp + Month                                
lm6 11 200.9728 32.90    0.6048198 0.5696057     Temp * Month                                

Both criteria favor lm3, which has the lowest AIC and the highest adjusted \(R^2\). The AICdelta column gives each model’s difference to the lowest AIC. As a rough rule of thumb, models within about 2 AIC units of each other are similarly well supported by the data (Burnham and Anderson, 2002, p. 70). Only lm2 falls in this range (0.5), so by the principle of parsimony, the simpler lm2 is just as defensible. This is supported by the coefficients of lm3: neither Temp nor I(Temp^2) is significant on its own, and their VIFs are above 200 (see variance inflation). lm1 lies just outside the 2-unit range (2.8), and the other models are more than 10 AIC units behind and clearly less supported.

Earlier, we compared models with an F-test using anova(). The F-test and selection criteria answer different questions. The F-test is a hypothesis test for two nested models: is there evidence that the additional terms improve the model, or could the improvement be due to chance? Selection criteria such as AIC do not test hypotheses. They rank any number of candidate models, which need not be nested, by how well they are expected to predict new data. The two approaches often agree, but not always. For example, the interaction between temperature and wind in lm8 is not significant (p = 0.09), but the AIC of lm8 (187.2) is lower than that of lm7, the model without the interaction (188.2). AIC includes a term whenever its expected gain in predictive accuracy outweighs the penalty, which is a lower bar than significance at the 5% level. Use the F-test when you want to test a specific hypothesis about a term, and selection criteria when you want to choose among several candidate models.

Stepwise selection

In the seminar, we explored manual backward and forward selection, where predictors are removed from or added to the model step by step according to a chosen criterion. Use one criterion consistently, for example AIC:

Backward elimination:

  • Start with a full model including potential transformations and polynomials
  • Remove the term whose removal lowers the AIC the most
  • Repeat until removing any further term would increase the AIC

Forward selection:

  • Start with a simple model (e.g., a single predictor)
  • Add the term that lowers the AIC the most
  • Repeat until adding any further term would increase the AIC

The function step() automates both procedures using AIC (e.g., step(lm3, direction = "backward")). Selecting terms by p-values is also common, but mixing p-values and AIC within the same procedure can lead to inconsistent decisions.

One advantage of doing model reductions by hand is that you can impose some logical structure on the process, based on your understanding of the data and the underlying processes.

Exhaustive search

An alternative to forward and backward selection is exhaustive model comparison, which evaluates all possible combinations of predictor variables rather than following a single stepwise search path. This reduces the risk of overlooking a better model simply because of earlier selection decisions. In R, the function dredge() from the MuMIn package automates this process and ranks candidate models using a criterion such as AIC.

dredge() requires that all candidate models are fitted to exactly the same observations. Setting options(na.action = "na.fail") makes R stop with an error if any model would drop observations because of missing values. This option applies to the whole R session, so we reset it after the model selection. We use the standardized predictors, so the coefficients of the selected models refer to an increase by one standard deviation. We rank the models by AICc instead of AIC (see the box below).

NoteAICc for small samples

AIC tends to favor overly complex models when the sample size is small relative to the number of estimated parameters. The corrected AICc adds an extra penalty for each parameter that grows as the sample size gets smaller. For large samples, AICc and AIC become nearly identical, so AICc can be used in general. A common rule of thumb is to prefer AICc when the number of observations is less than about 40 times the number of parameters. This is the case here: the full model fit_full below estimates 26 parameters (25 coefficients and the residual variance) from only 111 observations. AICc is the default criterion in dredge().

options(na.action = "na.fail")

# full (global) model: contains all terms that any candidate model may include
fit_full <- lm(logOzone ~ (Temp_scl * Wind_scl + Solar_scl) * Month, data = airq)

# fit all subsets of the global model and rank them by AICc
fit_all <- MuMIn::dredge(global.model = fit_full, rank = AICc)

The result is a list of competing models:

head(fit_all, n = 5)
Global model call: lm(formula = logOzone ~ (Temp_scl * Wind_scl + Solar_scl) * Month, 
    data = airq)
---
Model selection table 
    (Int) Mnt Slr_scl Tmp_scl Wnd_scl Mnt:Wnd_scl Tmp_scl:Wnd_scl df  logLik  AICc delta weight
143 3.367      0.2365  0.4681 -0.2197                    -0.09930  6 -77.967 168.7  0.00  0.750
15  3.416      0.2293  0.4686 -0.2190                              5 -80.413 171.4  2.65  0.199
80  3.482   +  0.1954  0.4944 -0.1406           +                 13 -73.074 175.9  7.16  0.021
144 3.420   +  0.2329  0.4710 -0.2162                    -0.09596 10 -76.912 176.0  7.28  0.020
208 3.469   +  0.2002  0.4919 -0.2188           +        -0.06214 14 -72.498 177.4  8.63  0.010
Models ranked by AICc(x) 

Each row is one model, sorted by AICc. The first columns show the estimated coefficients of the terms in that model. An empty cell means that the term is not included, and + marks an included factor term such as Month, which has several coefficients. The last columns give the number of estimated parameters (df), the log-likelihood, the AICc, the difference in AICc from the top model (delta), and the Akaike weight, the relative support for each model among all candidates. As for AIC, models within about 2 units of the top model are similarly well supported. Here, the second model, which lacks the interaction between temperature and wind, has a delta of 2.7, so the top model is somewhat better supported, but not by a wide margin.

The function get.models() refits selected models from the list. With subset = 1, it returns the top-ranked model; subset = 2 would return the second model, and so on. Because get.models() always returns a list of models, even if it contains only one, we take the first element with [[1]]:

lm_best <- get.models(fit_all, subset = 1)[[1]]
summary(lm_best)

Call:
lm(formula = logOzone ~ Solar_scl + Temp_scl + Wind_scl + Temp_scl:Wind_scl + 
    1, data = airq)

Residuals:
     Min       1Q   Median       3Q      Max 
-1.98683 -0.32080 -0.05444  0.30229  1.19024 

Coefficients:
                  Estimate Std. Error t value Pr(>|t|)    
(Intercept)        3.36700    0.05246  64.183  < 2e-16 ***
Solar_scl          0.23649    0.04998   4.731 6.92e-06 ***
Temp_scl           0.46809    0.05702   8.210 5.74e-13 ***
Wind_scl          -0.21969    0.05494  -3.999 0.000118 ***
Temp_scl:Wind_scl -0.09930    0.04544  -2.185 0.031076 *  
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.4998 on 106 degrees of freedom
Multiple R-squared:  0.6789,    Adjusted R-squared:  0.6668 
F-statistic: 56.03 on 4 and 106 DF,  p-value: < 2.2e-16
options(na.action = "na.omit")  # reset to R's default

The best model contains the interaction between temperature and wind, as AIC already suggested for lm8 (see AIC above), and in this model it is also significant (p = 0.031). In lm8, the same interaction was not significant (p = 0.09). The difference is that the best model also contains solar radiation. Solar radiation explains part of the variation in ozone that was left in the residuals of lm8. The residual standard error becomes smaller, and with it the standard error of the interaction. At the same time, the estimate of the interaction changes slightly. Together, this is enough for a similar effect to be distinguished from noise. Whether a term is significant therefore depends on the other terms in the model, and a non-significant term in one model is not evidence that it plays no role.

Automation does not relieve researchers of the responsibility for model selection. We must decide which predictors and candidate models are scientifically justified, choose an appropriate selection criterion, and interpret the results in context. Although criteria such as AIC provide an objective basis for comparison, defining the candidate models and deciding which model is most appropriate also require scientific judgment. The model ranked first by a selection criterion is not necessarily the best model for the research question.

TipIn practice: fitting a multiple regression

The following steps are a general guide, not a fixed recipe. Their order is not strict, and a later step may send you back to an earlier one, for example when the residuals call for a transformation or a different model. Keep in mind that each round of going back makes the p-values of the final model more optimistic, so treat them as descriptive and report how the model was found (Gelman and Loken, 2013).

  1. Explore the data with pairs() and cor(). Transform the response or predictors if relationships are curved or the spread increases with the level, as for logOzone.
  2. Fit candidate models based on your understanding of the data and check collinearity with vif() (see variance inflation).
  3. Test a specific term with anova(), or choose among the candidate models with AIC or AICc (see model selection).
  4. Check the residuals of the selected model with a residual plot and a QQ-plot (see model diagnostics).
  5. Interpret the coefficients with summary(). In models with interactions, they are easier to interpret if the continuous predictors are centered (see centered predictors).
  6. Visualize the effects: calculate fitted lines and confidence bands with effect() and plot them, back-transformed with exp() if the response was log-transformed (see visualizing effects).

References

Burnham, K.P., Anderson, D.R., 2002. Model selection and multimodel inference: A practical information-theoretic approach, 2nd ed. Springer, New York. https://doi.org/10.1007/b97636
Gelman, A., Loken, E., 2013. The garden of forking paths: Why multiple comparisons can be a problem, even when there is no “fishing expedition” or “p-hacking” and the research hypothesis was posited ahead of time. URL http://www.stat.columbia.edu/~gelman/research/unpublished/p_hacking.pdf
James, G., Witten, D., Hastie, T., Tibshirani, R., 2021. An introduction to statistical learning: With applications in R, 2nd ed, Springer texts in statistics. Springer, New York. https://doi.org/10.1007/978-1-0716-1418-1
Zuur, A.F., Ieno, E.N., Smith, G.M., 2007. Analysing ecological data, Statistics for biology and health. Springer, New York. https://doi.org/10.1007/978-0-387-45972-1