Skip to main content

4  Additive Effects

Regression analysis with more than one explanatory variable.


This chapter uses GLM notation (\(\eta\)). To focus on the concept of combining explanatory variables, only normal examples are shown (lm). For Poisson and binomial, try the explore mode of the interactive app at the bottom.

4.1 Summary

Scatter plot of systolic blood pressure (mmHg) against exercise (hours per week) for patients on drug A and B, each drug with its own regression line. The two lines fall with the same slope; the line of drug B lies lower than that of drug A.
Figure 4.1: One continuous and one categorical explanatory variable and the estimated line of each group.
(Exercise and systolic blood pressure of 40 patients with hypertension on two drugs.)

Mathematical formula:

\[\begin{align} \eta &= \beta_0 + \beta_1 \cdot x_1 + \beta_2 \cdot x_2 \\ \tag{1}\label{additiveslope}\\ x_2 &=\begin{cases}1 \quad \text{if B}\\ 0 \quad \text{otherwise} \end{cases} \end{align}\]

Code:

model <- lm(y ~ x + group, data)
import statsmodels.formula.api as smf
model = smf.ols("y ~ x + group", data).fit()
\(\eta\) — linear predictor

The linear combination of the explanatory variables and their coefficients.
For ordinary linear models, this is just the predicted value of the outcome (\(y\)).

\(x_1\) — explanatory variable (continuous)

The variable the outcome is regressed on.

\(x_2\) — explanatory variable (dummy)

Translates the groups into a number that can be used in the formula. It works like a switch: In group B, it is on (\(x_2 = 1\)) and adds \(\beta_2\) to \(\eta\); in group A (the reference group), it is off (\(x_2 = 0\)).

\(\beta_0\) — intercept

Value of the linear predictor (\(\eta\)), when \(x_1\) and \(x_2\) are zero.
Here, \(x_2\) is zero in group A (the reference group), so this is \(\eta\) in group A at \(x_1 = 0\).

\(\beta_1\) — slope

Change in the linear predictor (\(\eta\)), when \(x_1\) increases by one, while \(x_2\) stays the same.
Here, this change is the same in group A and group B: The lines of both groups are parallel.

\(\beta_2\) — slope
Change in the linear predictor (\(\eta\)), when \(x_2\) increases by one, while \(x_1\) stays the same.
Here, \(x_2\) can only increase from \(0\) (group A) to \(1\) (group B), so this is the difference in \(\eta\) between group B and group A, at any value of \(x_1\): The distance between the parallel lines.

With a continuous variable and a dummy variable in the same model, each group gets its own line. The coefficient \(\beta_2\) is then an offset from the reference group’s intercept:

Diagram of two parallel falling lines of eta against x1, group B below group A. A dot where the line of group A crosses x1 = 0 is labeled beta 0. In both groups, the fall from x1 = 1 to x1 = 2 is labeled beta 1. The vertical distance between the lines is labeled beta 2.
Figure 4.2: The intercept (\(\beta_0\)) is \(\eta\) in group A, when \(x_1 = 0\). The slope \(\beta_1\) is the same in both groups, and \(\beta_2\) is the distance between the parallel lines.

The two lines of A and B are then defined as follows:

Purpose of the coefficients.
Intercept Slope
A \(\beta_0\) \(\beta_1\)
B \(\beta_0 + \beta_2\) \(\beta_1\)

A model with a single slope for both groups is called a main effects model. It assumes the fitted lines are parallel. If the slopes differ, see the next chapter, interaction.

Fitted to the data of Figure 4.1, the model gives the following estimates:

model <- lm(y ~ x + group, data)
summary(model)$coefficients
              Estimate Std. Error   t value     Pr(>|t|)
(Intercept) 148.312850  1.8722743 79.215344 6.678341e-43
x            -3.180231  0.5977632 -5.320219 5.225802e-06
groupB       -9.872886  1.5350878 -6.431480 1.639695e-07
import statsmodels.formula.api as smf
model = smf.ols("y ~ x + group", data).fit()
print(model.summary().tables[1])
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
Intercept    148.3128      1.872     79.215      0.000     144.519     152.106
group[T.B]    -9.8729      1.535     -6.431      0.000     -12.983      -6.763
x             -3.1802      0.598     -5.320      0.000      -4.391      -1.969
==============================================================================

Note that Python names the row group[T.B], instead of groupB.

The intercept of the reference group (A) is given by (Intercept) (148.31) and the slope by x (-3.18). Group B starts 9.87 lower, so its intercept is 138.44. Apparently, this difference is significant (\(p = 1.64 \times 10^{-7}\)).

What if there are more than two groups?
Scatter plot of systolic blood pressure (mmHg) against exercise (hours per week) for patients on drug A, B and C, each drug with its own regression line. The three lines fall with the same slope; the line of drug C lies between those of drug A and B.
Figure 4.3: The data of Figure 4.1 with a third drug, and the estimated line of each drug.
(Exercise and systolic blood pressure of 60 patients with hypertension on three drugs.)

With more than two groups, every group except the reference group gets its own offset from the intercept, while all groups share the same slope:

model <- lm(y ~ x + group, threegroups)
summary(model)$coefficients
              Estimate Std. Error   t value     Pr(>|t|)
(Intercept) 147.459541  1.5520113 95.011900 1.398615e-63
x            -2.849519  0.4401263 -6.474322 2.546227e-08
groupB       -9.694976  1.5146846 -6.400656 3.364385e-08
groupC       -4.968832  1.4960663 -3.321264 1.581915e-03
model = smf.ols("y ~ x + group", threegroups).fit()
print(model.summary().tables[1])
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
Intercept    147.4595      1.552     95.012      0.000     144.350     150.569
group[T.B]    -9.6950      1.515     -6.401      0.000     -12.729      -6.661
group[T.C]    -4.9688      1.496     -3.321      0.002      -7.966      -1.972
x             -2.8495      0.440     -6.474      0.000      -3.731      -1.968
==============================================================================

Careful, these \(p\)-values only tell you whether the groups differ from the reference group.


To test the overall effect of group, use an omnibus test instead. This gives a single \(p\)-value for the question: “Is there any difference among group means?”

library("car")
Anova(model)
Anova Table (Type II tests)

Response: y
           Sum Sq Df F value    Pr(>F)    
x          938.19  1  41.917 2.546e-08 ***
group      917.73  2  20.502 2.086e-07 ***
Residuals 1253.40 56                      
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
import statsmodels.api as sm
print(sm.stats.anova_lm(model, typ=2))
               sum_sq    df          F        PR(>F)
group      917.733732   2.0  20.501521  2.085810e-07
x          938.186597   1.0  41.916848  2.546227e-08
Residual  1253.396960  56.0        NaN           NaN

Note that anova_lm only works for ordinary linear models. For a GLM, use .wald_test_terms(scalar=True) on the fitted model.

Apparently, there are significant differences between the groups (\(p = 2.09 \times 10^{-7}\)).


To determine which groups differ, we can perform pairwise comparisons. Because the lines are parallel, the difference between two groups is the same at any value of \(x\):

library("emmeans")
EMM <- emmeans(model, pairwise ~ group)
EMM$contrasts
 contrast estimate   SE df t.ratio p.value
 A - B        9.69 1.51 56   6.401 <0.0001
 A - C        4.97 1.50 56   3.321  0.0044
 B - C       -4.73 1.52 56  -3.119  0.0079

P value adjustment: tukey method for comparing a family of 3 estimates 

statsmodels has no equivalent of emmeans. The differences between the groups can be tested with t_test, and corrected for multiple testing with the studentized range distribution, as emmeans does:

import numpy as np
import pandas as pd
from scipy.stats import studentized_range

tt = model.t_test(["group[T.B] = 0", "group[T.C] = 0", "group[T.C] - group[T.B] = 0"])
t = tt.tvalue.ravel()
p = studentized_range.sf(np.abs(t) * np.sqrt(2), 3, model.df_resid)
print(pd.DataFrame({"estimate": tt.effect, "SE": tt.sd.ravel(), "t": t, "p (Tukey)": p},
                   index=["B - A", "C - A", "C - B"]))
       estimate        SE         t     p (Tukey)
B - A -9.694976  1.514685 -6.400656  1.003868e-07
C - A -4.968832  1.496066 -3.321264  4.443486e-03
C - B  4.726144  1.515058  3.119447  7.933007e-03

After multiple testing correction, all three groups differ significantly from each other.

For a complete analysis, refer to the tutorials at the bottom of the page.

Dry mass (g) of plants of varieties A and B, with and without treatment, shown as points with a horizontal line at each group mean. Variety B is heavier than variety A, and treated plants are slightly heavier than untreated plants in both varieties.
Figure 4.4: Two categorical variables and the estimated mean of each combination.
(Dry mass of 40 plants of two varieties, with and without fertilizer treatment.)

Mathematical formula:

\[\begin{align} \eta &= \beta_0 + \beta_1 \cdot x_1 + \beta_2 \cdot x_2 \\ \tag{2}\label{additivedummy}\\ x_1 &=\begin{cases}1 \quad \text{if B}\\ 0 \quad \text{otherwise} \end{cases}\\ x_2 &= \begin{cases}1 \quad \text{if treated}\\ 0 \quad \text{otherwise} \end{cases} \end{align}\]

Code:

model <- lm(y ~ group + treatment, data)
import statsmodels.formula.api as smf
model = smf.ols("y ~ group + treatment", data).fit()
\(\eta\) — linear predictor

The linear combination of the explanatory variables and their coefficients.
For ordinary linear models, this is just the predicted value of the outcome (\(y\)).

\(x_1, x_2\) — explanatory variables (dummy variables)

Translate both categorical variables into numbers that can be used in the formula. Each works like a switch: \(x_1\) is on in group B and adds \(\beta_1\) to \(\eta\); \(x_2\) is on for treated observations and adds \(\beta_2\); for untreated observations in group A, both are off.

\(\beta_0\) — intercept

Value of the linear predictor (\(\eta\)), when \(x_1\) and \(x_2\) are zero.
Here, both are zero for untreated observations in group A (the reference groups), so this is \(\eta\) in untreated group A.

\(\beta_1\) — slope

Change in the linear predictor (\(\eta\)), when \(x_1\) increases by one, while \(x_2\) stays the same.
Here, \(x_1\) can only increase from \(0\) (group A) to \(1\) (group B), so this is the difference in \(\eta\) between group B and group A, the same with and without treatment.

\(\beta_2\) — slope
Change in the linear predictor (\(\eta\)), when \(x_2\) increases by one, while \(x_1\) stays the same.
Here, \(x_2\) can only increase from \(0\) (untreated) to \(1\) (treated), so this is the difference in \(\eta\) between treated and untreated, the same in group A and group B.

With two categorical variables in the same model, both get their own dummy variable. Without interaction, their effects simply add up: The difference between treated and untreated (\(\beta_2\)) is the same in group A and group B:

Diagram with x1 at 0 (group A) and 1 (group B) and two parallel lines, untreated below treated. A dot for untreated group A is labeled beta 0. The rise from group A to group B is labeled beta 1, and the vertical distance between treated and untreated is labeled beta 2.
Figure 4.5: The intercept (\(\beta_0\)) is \(\eta\) in untreated group A. The slope \(\beta_1\) is the difference between group B and group A, and \(\beta_2\) is the difference between treated and untreated.

The means of the four combinations are then defined as follows:

Purpose of the coefficients.
Untreated Treated
A \(\beta_0\) \(\beta_0 + \beta_2\)
B \(\beta_0 + \beta_1\) \(\beta_0 + \beta_1 + \beta_2\)

A model in which the difference between treated and untreated is the same in both groups is called a main effects model. If that difference varies between groups, see the next chapter, interaction.

Fitted to the data of Figure 4.4, the model gives the following estimates:

model <- lm(y ~ group + treatment, data)
summary(model)$coefficients
               Estimate Std. Error   t value     Pr(>|t|)
(Intercept)  10.6729336  0.2213147 48.225135 5.271722e-35
groupB        1.9296313  0.2555523  7.550829 5.298221e-09
treatmentyes  0.4067254  0.2555523  1.591555 1.199937e-01
import statsmodels.formula.api as smf
model = smf.ols("y ~ group + treatment", data).fit()
print(model.summary().tables[1])
====================================================================================
                       coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------------
Intercept           10.6729      0.221     48.225      0.000      10.225      11.121
group[T.B]           1.9296      0.256      7.551      0.000       1.412       2.447
treatment[T.yes]     0.4067      0.256      1.592      0.120      -0.111       0.925
====================================================================================

Note that Python names the rows group[T.B] and treatment[T.yes], instead of groupB and treatmentyes.

The estimated mean of the reference group (untreated, group A) is given by (Intercept) (10.67). For group B, we have to add groupB (1.93), and for treated observations, we have to add treatmentyes (0.41). For treated observations in group B, we have to add both, and the mean becomes 13.01. Apparently, group B differs significantly from A (\(p = 5.30 \times 10^{-9}\)), but the treatment effect is not significant (\(p = 0.120\)).

For a complete analysis, refer to the tutorials at the bottom of the page.

Three-dimensional plot of dry mass (g) against added nitrogen (0 to 1 g) and phosphorus (0 to 1 g), with a flat, tilted regression plane through the points. Dry mass increases with both nitrogen and phosphorus.
Figure 4.6: Two continuous explanatory variables and the resulting regression plane.
(Dry mass of 60 plants, grown with different amounts of added nitrogen and phosphorus.)
3D plots like this one are only meant to build intuition. See what to expect on the exam.

Mathematical formula:

\[\begin{align} \eta &= \beta_0 + \beta_1 \cdot x_1 + \beta_2 \cdot x_2 \tag{3}\label{additiveslopeslope} \end{align}\]

Code:

model <- lm(y ~ x1 + x2, data)
import statsmodels.formula.api as smf
model = smf.ols("y ~ x1 + x2", data).fit()
\(\eta\) — linear predictor

The linear combination of the explanatory variables and their coefficients.
For ordinary linear models, this is just the predicted value of the outcome (\(y\)).

\(x_1, x_2\) — explanatory variables (continuous)

The variables the outcome is regressed on.

\(\beta_0\) — intercept

Value of the linear predictor (\(\eta\)), when \(x_1\) and \(x_2\) are zero.

\(\beta_1\) — slope

Change in the linear predictor (\(\eta\)), when \(x_1\) increases by one, while \(x_2\) stays the same.
Here, this change is the same at any value of \(x_2\).

\(\beta_2\) — slope
Change in the linear predictor (\(\eta\)), when \(x_2\) increases by one, while \(x_1\) stays the same.
Here, this change is the same at any value of \(x_1\).

With two continuous variables in the same model, each gets its own slope. Without interaction, the slope of one variable is the same at any value of the other. Instead of a line, the model is now a flat plane:

Diagram of a flat, tilted plane above x1 and x2, each from 0 to 1. A dot at the corner where both are 0 is labeled beta 0. Along x1, the plane rises by the same amount, labeled beta 1, at x2 = 0 and at x2 = 1. Its rise along x2 is labeled beta 2.
Figure 4.7: Visual interpretation of the coefficients when \(x_1\) and \(x_2\) are both continuous. The slope of \(x_1\) is \(\beta_1\) at any value of \(x_2\). With more variables, the same idea continues in more dimensions (a hyperplane), but it can no longer be drawn.

Grouping the terms shows that \(x_2\) only shifts the intercept; the slope of \(x_1\) stays the same:

\[\eta = \underbrace{(\beta_0 + \beta_2 \cdot x_2)}_{\text{intercept}} + \underbrace{\beta_1}_{\text{slope}} \cdot x_1\]

Example interpretation of the coefficients.
Intercept Slope
\(x_2 = 0\) \(\beta_0\) \(\beta_1\)
\(x_2 = 1\) \(\beta_0 + \beta_2\) \(\beta_1\)
\(x_2 = 2\) \(\beta_0 + 2 \cdot \beta_2\) \(\beta_1\)

A model in which the slope of \(x_1\) is the same at every value of \(x_2\) is called a main effects model. If the slope changes with \(x_2\), see the next chapter, interaction.

Fitted to the data of Figure 4.6, the model gives the following estimates:

model <- lm(y ~ x1 + x2, data)
summary(model)$coefficients
            Estimate Std. Error  t value     Pr(>|t|)
(Intercept) 2.195186  0.2173984 10.09752 2.631674e-14
x1          4.866548  0.3118129 15.60727 3.064375e-22
x2          3.733792  0.3120147 11.96672 3.487701e-17
import statsmodels.formula.api as smf
model = smf.ols("y ~ x1 + x2", data).fit()
print(model.summary().tables[1])
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
Intercept      2.1952      0.217     10.098      0.000       1.760       2.631
x1             4.8665      0.312     15.607      0.000       4.242       5.491
x2             3.7338      0.312     11.967      0.000       3.109       4.359
==============================================================================

The coefficient of \(x_1\), 4.87, estimates how much the mean of \(y\) changes when \(x_1\) increases by one unit while \(x_2\) stays the same. Likewise, the coefficient of \(x_2\), 3.73, estimates the change per unit increase in \(x_2\) while \(x_1\) stays the same. Both differ significantly from zero here.

For a complete analysis, refer to the tutorials at the bottom of the page.

4.2 Quiz

A researcher compares the blood pressure of patients on two drugs and finds no significant difference (\(p = 0.31\)). After adding the hours of exercise per week to the model, the estimated difference between the drugs is almost the same, but it is now significant (\(p = 0.002\)). What is the most likely explanation? (choose one)

A. Exercise was a confounder, so the first estimate was biased
B. Exercise explains much of the variation in blood pressure, so the difference between the drugs is estimated more precisely
C. Adding an explanatory variable always lowers the \(p\)-values of the others
D. The drugs differ more in patients who exercise more

The estimate hardly changed. What else does a test statistic depend on?

A researcher compares the blood pressure of patients on two drugs and finds no significant difference (\(p = 0.31\)). After adding the hours of exercise per week to the model, the estimated difference between the drugs is almost the same, but it is now significant (\(p = 0.002\)). What is the most likely explanation? (choose one)

A. Exercise was a confounder, so the first estimate was biased
B. Exercise explains much of the variation in blood pressure, so the difference between the drugs is estimated more precisely
C. Adding an explanatory variable always lowers the \(p\)-values of the others
D. The drugs differ more in patients who exercise more

A. A confounder changes the estimate itself (see omitted variable bias). Here, the estimated difference stayed almost the same.
B. The \(t\)-value is the estimate divided by its standard error. Without exercise in the model, the variation in blood pressure that is due to exercise ends up in the residual variance, which makes the standard error large. With exercise in the model, the residual variance is smaller, and so is the standard error. The tutorial on a linear model shows an example.
C. It can also raise them, for example when the added variable is strongly related to another explanatory variable. And adding variables until a result is significant is not a fixed plan (see limitations of hypothesis testing).
D. That would be an interaction. This model has none: It assumes the difference between the drugs is the same at every amount of exercise.

A binomial GLM without interaction models the probability of death of rats as a function of the concentration of a toxic gas (\(x_1\)) and sex (\(x_2\)), as in the tutorial on a binomial GLM. Which statement is correct? (choose one)

A. The difference in the probability of death between male and female rats is the same at every concentration
B. The difference in the log-odds of death between male and female rats is the same at every concentration
C. Plotted as probabilities, the curves of male and female rats are parallel
D. If the plotted curves are not parallel, the model must contain an interaction

On which scale is a GLM linear? See the formula of a binomial GLM.

A binomial GLM without interaction models the probability of death of rats as a function of the concentration of a toxic gas (\(x_1\)) and sex (\(x_2\)), as in the tutorial on a binomial GLM. Which statement is correct? (choose one)

A. The difference in the probability of death between male and female rats is the same at every concentration
B. The difference in the log-odds of death between male and female rats is the same at every concentration
C. Plotted as probabilities, the curves of male and female rats are parallel
D. If the plotted curves are not parallel, the model must contain an interaction

A. The effects add up on the scale of the linear predictor (\(\eta\)), which for a binomial GLM is the log-odds. Translated back to probabilities, the difference is not constant: In the tutorial, it is \(4.3\) percentage points at \(0\) ppm, but \(28.3\) at \(20\) ppm.
B. This is what ‘without interaction’ means in a GLM: \(\beta_2\) is added to \(\eta\) at any value of \(x_1\).
C. The lines are parallel on the scale of \(\eta\) only. As probabilities, both curves are squeezed between \(0\) and \(1\), so the distance between them changes.
D. Curves that are not parallel on the scale of the outcome are what a GLM without interaction looks like. Interaction means that the lines are not parallel on the scale of \(\eta\).

Interactive app

Practice the concepts covered in this chapter (the app does not include models with two continuous variables):

Regression tables

This app runs in your browser. The first time, your browser downloads about 50 MB, which can take a minute or more.

4.3 Apply your knowledge

Now analyze a dataset yourself. Start with the worked examples, then do the exercise:

  1. Save the data and qmd file in the same location on your computer.
  2. Open the qmd file in RStudio.
  3. Set working directory to source file location.
    (Session > Set Working Directory > To Source File Location)
  4. R will now read from the folder the qmd file is located, so you can just use read.csv("name-of-data.csv").

Under construction. Check back later.