Confounding, DAGs & Effect Modification
Which covariates belong in a regression model is a causal question, and the data cannot answer it alone. A directed acyclic graph (DAG) writes down what causes what, and the variables to adjust for, and the ones to leave out, follow from it. This page simulates a confounder, a mediator and a collider around one exposure with a known effect, shows what adjusting for each does to the estimate, and then separates effect modification from confounding.
Get the data
Section titled “Get the data”Download activity_cohort.csv and bp_drug_trial.csv into your working directory. Both tables are invented.
The cohort has 2,500 rows, one per adult, and seven columns: person_id, age in years (40 to 74), active (1 for regular physical activity reported at enrollment), bmi (body mass index in kg/m², measured at a clinic visit two years later), sbp (systolic blood pressure in mm Hg at that visit), asthma (1 for a diagnosis before enrollment) and admitted (1 for any hospital admission in the five years after the visit). The question is how much regular activity changes systolic blood pressure, and the person is the unit of analysis.
The simulation fixes the answer. Activity lowers BMI by 2 kg/m², each kg/m² of BMI raises systolic pressure by 1.5 mm Hg, and activity lowers pressure by a further 3 mm Hg through other routes. The total effect of activity is therefore −3 + (−2 × 1.5) = −6 mm Hg, and the direct effect, the part that does not pass through BMI, is −3. Older people are less often active, and each year of age adds 0.5 mm Hg. Admission is more likely with a higher pressure, without regular activity, and with asthma. Asthma has no effect on blood pressure. The seed of the simulation was chosen from 399 candidates as the one whose estimates lie closest to their large-sample values, so that sampling noise does not hide the structures. One real study of this size would usually miss the truth by more than the estimates below.
The outcome is continuous, and the equations for BMI and blood pressure are linear with no product term, so each effect is one number that holds for every person. That choice is deliberate. An odds ratio changes when a strong predictor of the outcome enters a logistic model, even with no confounding at all, and that shift would blur every comparison below.
The trial table has 4,000 rows, one per patient randomized to a blood pressure drug or to placebo, and five columns: person_id, high_baseline (1 for a systolic pressure of 160 mm Hg or more at entry), treated, sbp_change (the change in systolic pressure at 12 months, in mm Hg) and cv_event (1 for a cardiovascular event within five years). The sections on effect modification give its true values.
Write the diagram and ask it for the adjustment set
Section titled “Write the diagram and ask it for the adjustment set”A DAG has one node per variable and one arrow per direct causal effect. An arrow says that one variable can affect another. A missing arrow says that it cannot, and that is the stronger claim. The diagram of this cohort has eight arrows: age affects activity and blood pressure, activity affects BMI, blood pressure and admission, BMI affects blood pressure, and blood pressure and asthma affect admission.
In R, dagitty() reads the diagram as text, and the code writes each arrow as effect <- cause, which dagitty accepts as well as cause -> effect. adjustmentSets() returns the covariate sets that identify an effect, with type = "all" for every valid set in place of the default minimal ones, and paths() lists each path between two nodes and whether it is open. networkx has d-separation and no function that lists adjustment sets, so the Python code applies the back-door criterion to every subset of the covariates that holds no descendant of the exposure. Such a set qualifies when it d-separates exposure and outcome in the graph without the arrows that leave the exposure.
library(dagitty)library(ggdag)library(ggplot2)
cohort <- read.csv("activity_cohort.csv")trial <- read.csv("bp_drug_trial.csv")dir.create("outputs", showWarnings = FALSE)arrows <- " active <- age sbp <- age bmi <- active sbp <- bmi sbp <- active admitted <- active admitted <- sbp admitted <- asthma"dag <- dagitty(paste("dag {", arrows, "}"))exposures(dag) <- "active"outcomes(dag) <- "sbp"cat("Adjustment sets for the total effect:\n")print(adjustmentSets(dag, effect = "total", type = "all"))cat("Minimal adjustment set for the direct effect:\n")print(adjustmentSets(dag, effect = "direct"))activity_paths <- paths(dag, "active", "sbp")cat("Paths between active and sbp, and whether each is open:\n")cat(sprintf(" %-26s %s\n", activity_paths$paths, activity_paths$open), sep = "")for (candidate in list(c("age", "bmi"), c("age", "admitted"))) { cat(sprintf("Is {%s} an adjustment set for the total effect? %s\n", paste(candidate, collapse = ", "), isAdjustmentSet(dag, candidate)))}Adjustment sets for the total effect:{ age }{ age, asthma }Minimal adjustment set for the direct effect:{ age, bmi }Paths between active and sbp, and whether each is open: active -> admitted <- sbp FALSE active -> bmi -> sbp TRUE active -> sbp TRUE active <- age -> sbp TRUEIs {age, bmi} an adjustment set for the total effect? FALSEIs {age, admitted} an adjustment set for the total effect? FALSEfrom itertools import combinationsfrom pathlib import Path
import matplotlib.pyplot as pltimport networkx as nximport numpy as npimport pandas as pdimport statsmodels.formula.api as smffrom scipy import stats
cohort = pd.read_csv("activity_cohort.csv")trial = pd.read_csv("bp_drug_trial.csv")output = Path("outputs")output.mkdir(exist_ok=True)
def backdoor_sets(graph, exposure, outcome, measured): """List every set of measured covariates that meets the criterion.
Args: graph: A networkx DiGraph without cycles. exposure: The name of the exposure node. outcome: The name of the outcome node. measured: The names of the measured nodes.
Returns: A list of the valid sets, written as text. """ backdoor_graph = graph.copy() backdoor_graph.remove_edges_from(list(graph.out_edges(exposure))) excluded = nx.descendants(graph, exposure) | {exposure, outcome} allowed = [node for node in measured if node not in excluded] found = [] for size in range(len(allowed) + 1): for subset in combinations(allowed, size): if nx.is_d_separator(backdoor_graph, exposure, outcome, set(subset)): found.append("{" + ", ".join(subset) + "}") return found
edges = [("age", "active"), ("age", "sbp"), ("active", "bmi"), ("bmi", "sbp"), ("active", "sbp"), ("active", "admitted"), ("sbp", "admitted"), ("asthma", "admitted")]dag = nx.DiGraph(edges)measured = sorted(dag.nodes)print("Back-door sets for the total effect: " + "; ".join(backdoor_sets(dag, "active", "sbp", measured)))Back-door sets for the total effect: {age}; {age, asthma}Two sets identify the total effect: { age } and { age, asthma }. Age must be in the model. Asthma is optional, because it touches blood pressure through admission only. BMI and admission appear in neither set, and isAdjustmentSet() confirms that adding either one to age breaks the adjustment.
The R output lists the four paths between activity and blood pressure. The two that leave activity along an arrow, active -> sbp and active -> bmi -> sbp, carry the effect, and together they are the total effect. active <- age -> sbp is a back-door path: it is open, it is not causal, and adjusting for age closes it. active -> admitted <- sbp is closed, because two arrowheads meet at admission, and it stays closed as long as nobody conditions on admission. For the direct effect the set is { age, bmi }, because the question changed.
The same objects draw the diagram. tidy_dagitty() of ggdag turns the dagitty object into a table that ggplot2 can plot, and networkx draws on Matplotlib axes with fixed coordinates.
coordinates(dag) <- list( x = c(age = 2, bmi = 2, active = 1, sbp = 3, admitted = 2, asthma = 3), y = c(age = 3.6, bmi = 2.8, active = 2, sbp = 2, admitted = 1, asthma = 1))roles <- c(active = "Exposure", sbp = "Outcome", age = "Confounder", bmi = "Mediator", admitted = "Collider", asthma = "Other cause")role_colors <- c(Exposure = "#1f4e5f", Outcome = "#55a868", Confounder = "#c44e52", Mediator = "#dd8452", Collider = "#8172b3", "Other cause" = "gray50")tidy_dag <- tidy_dagitty(dag)tidy_dag$data$role <- factor(roles[tidy_dag$data$name], levels = roles)dag_plot <- ggplot(tidy_dag, aes(x = x, y = y, xend = xend, yend = yend)) + geom_dag_edges() + geom_dag_point(aes(color = role), size = 20) + geom_dag_text(color = "white", size = 3) + scale_color_manual(values = role_colors, name = NULL) + guides(color = guide_legend(override.aes = list(size = 5))) + theme_dag()ggsave("outputs/activity-dag-r.png", dag_plot, width = 7, height = 4.2, dpi = 150)
positions = {"age": (2, 3.6), "bmi": (2, 2.8), "active": (1, 2), "sbp": (3, 2), "admitted": (2, 1), "asthma": (3, 1)}roles = {"Exposure": ("active", "#1f4e5f"), "Outcome": ("sbp", "#55a868"), "Confounder": ("age", "#c44e52"), "Mediator": ("bmi", "#dd8452"), "Collider": ("admitted", "#8172b3"), "Other cause": ("asthma", "0.5")}figure, axes = plt.subplots(figsize=(7, 4.2))nx.draw_networkx_edges(dag, positions, ax=axes, node_size=2600, arrowsize=16, width=1.4)for role, (node, color) in roles.items(): nx.draw_networkx_nodes(dag, positions, nodelist=[node], ax=axes, node_size=2600, node_color=color, label=role)nx.draw_networkx_labels(dag, positions, ax=axes, font_size=9, font_color="white")axes.legend(loc="center left", bbox_to_anchor=(1.0, 0.5), frameon=False, markerscale=0.3)axes.margins(0.15)axes.axis("off")figure.tight_layout()figure.savefig(output / "activity-dag-python.png", dpi=150)plt.close(figure)
A confounder: adjust for it
Section titled “A confounder: adjust for it”Age is a common cause of activity and blood pressure. A small function prints one coefficient with its interval beside the truth, and every section below uses it.
#' Print one coefficient of a linear model with its 95% limits.#'#' @param label Text that names the model.#' @param fit A fitted lm object.#' @param term The name of the coefficient.#' @param truth Text that gives the true value.#' @return The estimate, invisibly.PrintEffect <- function(label, fit, term, truth) { limits <- confint(fit)[term, ] cat(sprintf("%-31s %6.2f [%6.2f, %6.2f] truth %s\n", label, coef(fit)[[term]], limits[1], limits[2], truth)) invisible(coef(fit)[[term]])}
mean_age <- tapply(cohort$age, cohort$active, mean)cat(sprintf("Mean age: inactive %.1f, active %.1f\n", mean_age[["0"]], mean_age[["1"]]))age_fit <- lm(sbp ~ active + age, data = cohort)PrintEffect("sbp ~ active", lm(sbp ~ active, data = cohort), "active", "-6")PrintEffect("sbp ~ active + age", age_fit, "active", "-6")Mean age: inactive 61.1, active 53.5sbp ~ active -9.64 [-10.70, -8.57] truth -6sbp ~ active + age -5.97 [ -7.05, -4.89] truth -6def print_effect(label, fit, term, truth): """Print one coefficient of a linear model with its 95% limits.
Args: label: Text that names the model. fit: A fitted statsmodels regression result. term: The name of the coefficient. truth: Text that gives the true value.
Returns: The estimate. """ lower, upper = fit.conf_int().loc[term] print(f"{label:<31} {fit.params[term]:6.2f} [{lower:6.2f}, " f"{upper:6.2f}] truth {truth}") return fit.params[term]
mean_age = cohort.groupby("active")["age"].mean()print(f"Mean age: inactive {mean_age[0]:.1f}, active {mean_age[1]:.1f}")age_fit = smf.ols("sbp ~ active + age", data=cohort).fit()print_effect("sbp ~ active", smf.ols("sbp ~ active", data=cohort).fit(), "active", "-6")print_effect("sbp ~ active + age", age_fit, "active", "-6")Mean age: inactive 61.1, active 53.5sbp ~ active -9.64 [-10.70, -8.57] truth -6sbp ~ active + age -5.97 [ -7.05, -4.89] truth -6Active people are younger, 53.5 years on average against 61.1. The crude comparison credits activity with part of what youth does: it returns −9.64 mm Hg, and its interval from −10.70 to −8.57 excludes the true −6. With age in the model the estimate is −5.97, and the interval from −7.05 to −4.89 covers the truth. The age gap of 7.6 years at 0.5 mm Hg per year is 3.8 mm Hg, close to the 3.67 that separates the two estimates. The multiple regression page covers the mechanics of this adjustment and its diagnostics.
The adjusted estimate has a causal reading only under the diagram. No unmeasured variable may cause both activity and blood pressure, age must enter the model in the right form, and active and inactive people must both exist at every age. The data cannot confirm the first condition, and a later section shows why.
A mediator: leave it out of the total effect
Section titled “A mediator: leave it out of the total effect”BMI lies on a path from activity to blood pressure. It was measured two years after enrollment, so it is partly a result of the exposure. Adjusting for it holds fixed one of the routes by which activity works.
bmi_fit <- lm(bmi ~ active + age, data = cohort)mediator_fit <- lm(sbp ~ active + age + bmi, data = cohort)PrintEffect("bmi ~ active + age", bmi_fit, "active", "-2")PrintEffect("sbp ~ active + age", age_fit, "active", "-6 (total)")PrintEffect("sbp ~ active + age + bmi", mediator_fit, "active", "-3 (direct)")PrintEffect(" bmi in that model", mediator_fit, "bmi", "1.5")cat(sprintf("Through BMI: %.2f x %.2f = %.2f, truth -3\n", coef(bmi_fit)[["active"]], coef(mediator_fit)[["bmi"]], coef(bmi_fit)[["active"]] * coef(mediator_fit)[["bmi"]]))bmi ~ active + age -1.94 [ -2.23, -1.65] truth -2sbp ~ active + age -5.97 [ -7.05, -4.89] truth -6 (total)sbp ~ active + age + bmi -3.17 [ -4.20, -2.15] truth -3 (direct) bmi in that model 1.44 [ 1.31, 1.58] truth 1.5Through BMI: -1.94 x 1.44 = -2.79, truth -3bmi_fit = smf.ols("bmi ~ active + age", data=cohort).fit()mediator_fit = smf.ols("sbp ~ active + age + bmi", data=cohort).fit()print_effect("bmi ~ active + age", bmi_fit, "active", "-2")print_effect("sbp ~ active + age", age_fit, "active", "-6 (total)")print_effect("sbp ~ active + age + bmi", mediator_fit, "active", "-3 (direct)")print_effect(" bmi in that model", mediator_fit, "bmi", "1.5")through_bmi = bmi_fit.params["active"] * mediator_fit.params["bmi"]print(f"Through BMI: {bmi_fit.params['active']:.2f} x " f"{mediator_fit.params['bmi']:.2f} = {through_bmi:.2f}, truth -3")bmi ~ active + age -1.94 [ -2.23, -1.65] truth -2sbp ~ active + age -5.97 [ -7.05, -4.89] truth -6 (total)sbp ~ active + age + bmi -3.17 [ -4.20, -2.15] truth -3 (direct) bmi in that model 1.44 [ 1.31, 1.58] truth 1.5Through BMI: -1.94 x 1.44 = -2.79, truth -3Activity lowers BMI by 1.94 kg/m², near the true 2. With BMI in the model the activity coefficient falls from −5.97 to −3.17, and its interval, −4.20 to −2.15, excludes the total effect of −6. The number −3.17 is a good estimate of the direct effect of −3, which answers a different question. A reader who wants to know what becoming active does to blood pressure needs the total effect, and the model with BMI removes the part of it that works through weight. The last line recovers that part as the product of the two coefficients, −2.79, and −3.17 + (−2.79) = −5.96 is the total up to rounding.
The direct effect has a condition of its own: every common cause of the mediator and the outcome must be in the model. That holds in this simulation and is rarely certain in practice. If an unmeasured diet affected both BMI and blood pressure, adjusting for BMI would open the path from activity through BMI to diet and on to blood pressure, and −3.17 would not estimate the direct effect either.
A collider: leave it out of the model and of the sample
Section titled “A collider: leave it out of the model and of the sample”Admission is a common effect of activity and blood pressure. The two arrows meet there, and the path through it is closed until someone conditions on it. A model term for admitted conditions on it, and so does a study that recruits its participants in the hospital. Asthma shows the second case most clearly, because its true effect on blood pressure is zero, and the d-separation query states what the diagram expects for it.
admitted_share <- tapply(cohort$admitted, cohort$active, mean)admitted_sbp <- tapply(cohort$sbp, cohort$admitted, mean)cat(sprintf("Admitted: %.3f of the inactive, %.3f of the active\n", admitted_share[["0"]], admitted_share[["1"]]))cat(sprintf("Mean sbp: %.1f not admitted, %.1f admitted\n", admitted_sbp[["0"]], admitted_sbp[["1"]]))collider_fit <- lm(sbp ~ active + age + admitted, data = cohort)PrintEffect("sbp ~ active + age", age_fit, "active", "-6")PrintEffect("sbp ~ active + age + admitted", collider_fit, "active", "-6")cat(sprintf("asthma and sbp d-separated given nothing: %s\n", dseparated(dag, "asthma", "sbp", c())))cat(sprintf("asthma and sbp d-separated given admitted: %s\n", dseparated(dag, "asthma", "sbp", "admitted")))inpatients <- cohort[cohort$admitted == 1, ]PrintEffect("Asthma, everyone", lm(sbp ~ asthma, data = cohort), "asthma", "0")PrintEffect("Asthma, admitted only", lm(sbp ~ asthma, data = inpatients), "asthma", "0")PrintEffect("Activity, admitted only", lm(sbp ~ active + age, data = inpatients), "active", "-6")Admitted: 0.280 of the inactive, 0.064 of the activeMean sbp: 123.9 not admitted, 137.9 admittedsbp ~ active + age -5.97 [ -7.05, -4.89] truth -6sbp ~ active + age + admitted -3.95 [ -5.01, -2.88] truth -6asthma and sbp d-separated given nothing: TRUEasthma and sbp d-separated given admitted: FALSEAsthma, everyone 0.40 [ -1.39, 2.19] truth 0Asthma, admitted only -4.88 [ -7.50, -2.26] truth 0Activity, admitted only -3.02 [ -6.02, -0.03] truth -6admitted_share = cohort.groupby("active")["admitted"].mean()admitted_sbp = cohort.groupby("admitted")["sbp"].mean()print(f"Admitted: {admitted_share[0]:.3f} of the inactive, " f"{admitted_share[1]:.3f} of the active")print(f"Mean sbp: {admitted_sbp[0]:.1f} not admitted, " f"{admitted_sbp[1]:.1f} admitted")collider_fit = smf.ols("sbp ~ active + age + admitted", data=cohort).fit()print_effect("sbp ~ active + age", age_fit, "active", "-6")print_effect("sbp ~ active + age + admitted", collider_fit, "active", "-6")print("asthma and sbp d-separated given nothing: " f"{nx.is_d_separator(dag, 'asthma', 'sbp', set())}")print("asthma and sbp d-separated given admitted: " f"{nx.is_d_separator(dag, 'asthma', 'sbp', {'admitted'})}")inpatients = cohort[cohort["admitted"] == 1]print_effect("Asthma, everyone", smf.ols("sbp ~ asthma", data=cohort).fit(), "asthma", "0")print_effect("Asthma, admitted only", smf.ols("sbp ~ asthma", data=inpatients).fit(), "asthma", "0")print_effect("Activity, admitted only", smf.ols("sbp ~ active + age", data=inpatients).fit(), "active", "-6")Admitted: 0.280 of the inactive, 0.064 of the activeMean sbp: 123.9 not admitted, 137.9 admittedsbp ~ active + age -5.97 [ -7.05, -4.89] truth -6sbp ~ active + age + admitted -3.95 [ -5.01, -2.88] truth -6asthma and sbp d-separated given nothing: Trueasthma and sbp d-separated given admitted: FalseAsthma, everyone 0.40 [ -1.39, 2.19] truth 0Asthma, admitted only -4.88 [ -7.50, -2.26] truth 0Activity, admitted only -3.02 [ -6.02, -0.03] truth -6Of the inactive people 28.0% were admitted against 6.4% of the active, and the mean pressure is 137.9 mm Hg among the admitted against 123.9 among the rest. With admitted in the model the activity coefficient moves from −5.97 to −3.95, and the interval from −5.01 to −2.88 excludes −6. A third of the effect has gone, and none of it passed through admission, which came after the blood pressure measurement.
The model now compares active and inactive people within each level of admission. An active person who was admitted anyway needed another reason to be there, and a high pressure is the likely one, while an inactive person who stayed out of hospital more often had a low pressure. Within each level, activity and pressure acquire a positive association that does not exist in the cohort. It adds to the true negative effect, and the coefficient moves toward zero.
Selection through the study design
Section titled “Selection through the study design”The diagram says that asthma and blood pressure are independent in the whole cohort and dependent once admission is known, and the data do not contradict it. Across all 2,500 people, those with asthma have a pressure 0.40 mm Hg higher than those without, and the interval from −1.39 to 2.19 covers the true zero. Among the admitted people the difference is −4.88 mm Hg, with an interval from −7.50 to −2.26. A hospital-based study would report that asthma lowers blood pressure by about 5 mm Hg. A patient with asthma had a reason for admission that required no high pressure, and the patients without asthma were more often there because of their pressure. This is Berkson’s bias.
The effect of activity suffers in the same way. Among admitted people the age-adjusted estimate is −3.02 where the truth is −6, with an interval from −6.02 to −0.03. No covariate in the admitted sample repairs this, because the people who would restore the comparison were never recruited. The bias analysis page corrects an estimate for selection bias when the selection probabilities can be estimated or assumed.
Check the diagram against the data
Section titled “Check the diagram against the data”Every missing arrow implies an independence that the data can contradict. impliedConditionalIndependencies() lists one for each pair of nodes with no arrow between them. One line says that age and BMI are independent given activity, which a regression of BMI on activity and age can test: the age coefficient should be zero. The code then adds a cause that nobody measured, habits, which stands for anything that makes a person active and also lowers blood pressure by another route, such as diet.
cat("Implied conditional independencies:\n")print(impliedConditionalIndependencies(dag))PrintEffect("age in bmi ~ active + age", bmi_fit, "age", "0")dag_hidden <- dagitty(paste( "dag { habits [latent] active <- habits sbp <- habits", arrows, "}"))exposures(dag_hidden) <- "active"outcomes(dag_hidden) <- "sbp"implied <- sapply(impliedConditionalIndependencies(dag), format)implied_hidden <- sapply(impliedConditionalIndependencies(dag_hidden), format)cat(sprintf("Same implied independencies with a hidden cause: %s\n", setequal(implied, implied_hidden)))cat(sprintf("Adjustment sets with a hidden cause: %d\n", length(adjustmentSets(dag_hidden))))Implied conditional independencies:actv _||_ asthadmt _||_ age | actv, sbpadmt _||_ bmi | actv, sbpage _||_ asthage _||_ bmi | actvasth _||_ bmiasth _||_ sbpage in bmi ~ active + age 0.00 [ -0.01, 0.02] truth 0Same implied independencies with a hidden cause: TRUEAdjustment sets with a hidden cause: 0print("age and bmi d-separated given active: " f"{nx.is_d_separator(dag, 'age', 'bmi', {'active'})}")print_effect("age in bmi ~ active + age", bmi_fit, "age", "0")dag_hidden = nx.DiGraph(edges + [("habits", "active"), ("habits", "sbp")])print("With a hidden cause, age and bmi d-separated given active: " f"{nx.is_d_separator(dag_hidden, 'age', 'bmi', {'active'})}")print("Back-door sets with a hidden cause: " f"{len(backdoor_sets(dag_hidden, 'active', 'sbp', measured))}")age and bmi d-separated given active: Trueage in bmi ~ active + age 0.00 [ -0.01, 0.02] truth 0With a hidden cause, age and bmi d-separated given active: TrueBack-door sets with a hidden cause: 0dagitty abbreviates the node names. The seven lines are the seven pairs of variables with no arrow between them: six variables make 15 pairs, and eight pairs have an arrow. The data do not contradict the line age _||_ bmi | actv, with an age coefficient of 0.00 kg/m² per year and an interval from −0.01 to 0.02. The line asth _||_ sbp is the regression of blood pressure on asthma in the whole cohort, 0.40 with an interval that covers zero. An interval that excluded zero would have been evidence against the diagram, for example a missing arrow from age to BMI.
A diagram that the data do not contradict is not thereby proven. These checks test the missing arrows between measured variables and say nothing about a variable that is not in the table. With habits added, the implied independencies among the measured variables are the same seven, and networkx still finds age and BMI d-separated given activity, so no test on this table can tell the two diagrams apart. Under the second diagram no set of measured covariates identifies the effect, and both languages print zero. The age-adjusted −5.97 would then carry a bias of unknown size, with the same data and the same passed checks. The assumption of no unmeasured confounding rests on subject knowledge, and the bias analysis page computes how strong a hidden cause would have to be to explain an estimate away.
Do not adjust for everything
Section titled “Do not adjust for everything”A model with every available covariate looks careful. Here it holds a confounder, a mediator, a collider and a cause of the collider. The code prints its coefficient table, then adds one variable at a time to the correct model and applies two common selection rules: keep a covariate when its p-value is small, or keep it when it changes the exposure coefficient by more than 10%.
full_fit <- lm(sbp ~ active + age + bmi + admitted + asthma, data = cohort)print(round(summary(full_fit)$coefficients, 3))cat(sprintf("%-10s %-12s %-8s %s\n", "Added", "Active coef", "Change", "p of the added term"))reference <- coef(age_fit)[["active"]]for (added in c("bmi", "admitted", "asthma")) { fit <- lm(reformulate(c("active", "age", added), "sbp"), data = cohort) change <- sprintf("%+.0f%%", 100 * (coef(fit)[["active"]] / reference - 1)) cat(sprintf("%-10s %-12.2f %-8s %.2g\n", added, coef(fit)[["active"]], change, summary(fit)$coefficients[added, "Pr(>|t|)"]))}PrintEffect("age in sbp ~ active + age", age_fit, "age", "0.5 with activity fixed")PrintEffect("age in sbp ~ age", lm(sbp ~ age, data = cohort), "age", "0.5 plus the path through activity") Estimate Std. Error t value Pr(>|t|)(Intercept) 64.200 2.374 27.037 0.000active -1.582 0.519 -3.047 0.002age 0.453 0.024 18.900 0.000bmi 1.325 0.067 19.850 0.000admitted 9.148 0.666 13.746 0.000asthma -1.594 0.747 -2.133 0.033Added Active coef Change p of the added termbmi -3.17 -47% 3e-90admitted -3.95 -34% 3.7e-49asthma -5.99 +0% 0.19age in sbp ~ active + age 0.48 [ 0.43, 0.54] truth 0.5 with activity fixedage in sbp ~ age 0.59 [ 0.54, 0.64] truth 0.5 plus the path through activityfull_fit = smf.ols("sbp ~ active + age + bmi + admitted + asthma", data=cohort).fit()print(full_fit.summary2().tables[1].iloc[:, :4].round(3))print(f"{'Added':<10} {'Active coef':<12} {'Change':<8} " "p of the added term")reference = age_fit.params["active"]for added in ("bmi", "admitted", "asthma"): fit = smf.ols(f"sbp ~ active + age + {added}", data=cohort).fit() change = f"{100 * (fit.params['active'] / reference - 1):+.0f}%" print(f"{added:<10} {fit.params['active']:<12.2f} {change:<8} " f"{fit.pvalues[added]:.2g}")print_effect("age in sbp ~ active + age", age_fit, "age", "0.5 with activity fixed")print_effect("age in sbp ~ age", smf.ols("sbp ~ age", data=cohort).fit(), "age", "0.5 plus the path through activity") Coef. Std.Err. t P>|t|Intercept 64.200 2.374 27.037 0.000active -1.582 0.519 -3.047 0.002age 0.453 0.024 18.900 0.000bmi 1.325 0.067 19.850 0.000admitted 9.148 0.666 13.746 0.000asthma -1.594 0.747 -2.133 0.033Added Active coef Change p of the added termbmi -3.17 -47% 3e-90admitted -3.95 -34% 3.7e-49asthma -5.99 +0% 0.19age in sbp ~ active + age 0.48 [ 0.43, 0.54] truth 0.5 with activity fixedage in sbp ~ age 0.59 [ 0.54, 0.64] truth 0.5 plus the path through activityEvery coefficient in the first table has a p-value below 0.05. The activity coefficient, −1.582, is neither the total effect of −6 nor the direct effect of −3. The BMI coefficient is 1.325 with a standard error of 0.067, which puts the true 1.5 about 2.6 standard errors away. Without admission in the model it was 1.44, with an interval that covers 1.5, so the term for admission moved it: admission is a consequence of blood pressure, and conditioning on it distorts the coefficients of the causes of blood pressure. The admission coefficient of 9.148 describes who gets admitted, since admission came after the measurement and cannot have raised it. Asthma has a coefficient of −1.594 with p = 0.033 and a true effect of zero.
The second table shows why a statistical selection rule cannot replace the diagram. BMI enters with p = 3e-90 and changes the activity coefficient by 47%. Admission enters with p = 3.7e-49 and changes it by 34%. Both pass the p-value rule and the 10% rule, and both are wrong for the total effect. Age, the one covariate that belongs, would pass for the same reason, since it moved the crude −9.64 to −5.97. The rules measure association, and a confounder, a mediator and a collider differ only in the direction of their arrows. Asthma fails both rules, with p = 0.19 and a change of 0%, and it is the one extra covariate that the diagram allows.
The coefficient of a confounder is not that variable’s effect either. In the correct model the age coefficient is 0.48, the change in pressure per year of age with activity held fixed, while age also acts through activity, and the regression on age alone gives 0.59 for both routes together. The model was built to close the back-door paths of activity, and nothing in it closes the back-door paths of age. Report the exposure coefficient as the result and the other coefficients as adjustment.
Effect modification is not confounding
Section titled “Effect modification is not confounding”A confounder distorts one effect, and adjustment removes the distortion. An effect modifier is a variable across whose levels the effect itself differs, so there is nothing to remove and there are two effects to report.
The trial makes the difference visible, because randomization rules confounding out. In the simulation the drug changes systolic pressure by −6 mm Hg in patients with a lower baseline and by −12 mm Hg in patients with a high baseline. About 40% of patients have a high baseline, so the average effect in the trial population is 0.6 × (−6) + 0.4 × (−12) = −8.4 mm Hg. The code estimates the effect in each stratum, then fits one model with the product term treated:high_baseline, whose coefficient is the difference between the two stratum effects.
lower <- trial[trial$high_baseline == 0, ]high <- trial[trial$high_baseline == 1, ]product_fit <- lm(sbp_change ~ treated * high_baseline, data = trial)PrintEffect("Lower baseline", lm(sbp_change ~ treated, data = lower), "treated", "-6")PrintEffect("High baseline", lm(sbp_change ~ treated, data = high), "treated", "-12")PrintEffect("Product term", product_fit, "treated:high_baseline", "-6")PrintEffect("Everyone, treated only", lm(sbp_change ~ treated, data = trial), "treated", "-8.4")PrintEffect("Everyone, modifier as covariate", lm(sbp_change ~ treated + high_baseline, data = trial), "treated", "-8.4")Lower baseline -6.14 [ -7.04, -5.25] truth -6High baseline -12.01 [-13.06, -10.95] truth -12Product term -5.86 [ -7.25, -4.48] truth -6Everyone, treated only -8.59 [ -9.30, -7.87] truth -8.4Everyone, modifier as covariate -8.53 [ -9.22, -7.85] truth -8.4lower = trial[trial["high_baseline"] == 0]high = trial[trial["high_baseline"] == 1]product_fit = smf.ols("sbp_change ~ treated * high_baseline", data=trial).fit()print_effect("Lower baseline", smf.ols("sbp_change ~ treated", data=lower).fit(), "treated", "-6")print_effect("High baseline", smf.ols("sbp_change ~ treated", data=high).fit(), "treated", "-12")print_effect("Product term", product_fit, "treated:high_baseline", "-6")print_effect("Everyone, treated only", smf.ols("sbp_change ~ treated", data=trial).fit(), "treated", "-8.4")print_effect("Everyone, modifier as covariate", smf.ols("sbp_change ~ treated + high_baseline", data=trial).fit(), "treated", "-8.4")Lower baseline -6.14 [ -7.04, -5.25] truth -6High baseline -12.01 [-13.06, -10.95] truth -12Product term -5.86 [ -7.25, -4.48] truth -6Everyone, treated only -8.59 [ -9.30, -7.87] truth -8.4Everyone, modifier as covariate -8.53 [ -9.22, -7.85] truth -8.4Randomization gave a high baseline pressure the same chance in both arms, so it cannot confound the comparison. Adding it as a covariate barely moves the overall estimate: −8.59 without it and −8.53 with it, both near the true average of −8.4. Yet the effect is −6.14 mm Hg (−7.04 to −5.25) in patients with a lower baseline and −12.01 (−13.06 to −10.95) in patients with a high baseline. The product term puts the gap at −5.86, with an interval from −7.25 to −4.48 that excludes zero and covers the true −6.
The overall −8.59 is a valid average for a population with this mix of patients, and it describes neither group well. A population with a different share of high baseline pressures has a different average effect, which is why a modifier matters when a result is carried from one population to another. Report the stratum effects with their intervals, and the product term as the estimate of their difference. One variable can play both parts: if activity lowered pressure more in older people, age in the cohort would need adjustment as a confounder and separate estimates as a modifier.
Effect modification depends on the scale
Section titled “Effect modification depends on the scale”For a binary outcome an effect can be a difference of risks or a ratio of risks, and a modifier on one scale need not be a modifier on the other. In the simulation the five-year risk of a cardiovascular event on placebo is 8% with a lower baseline pressure and 30% with a high one, and the drug multiplies the risk by 0.6 in both groups. The true risk ratio is therefore 0.6 in both strata, and the true risk differences are −0.032 and −0.120. The code computes both measures in each stratum with Wald limits, then the ratio of the two risk ratios and the difference of the two risk differences.
z <- qnorm(0.975)strata <- data.frame()for (stratum in list(lower, high)) { events <- tapply(stratum$cv_event, stratum$treated, sum) people <- tapply(stratum$cv_event, stratum$treated, length) risk <- events / people strata <- rbind(strata, data.frame( drug = risk[["1"]], placebo = risk[["0"]], log_rr = log(risk[["1"]] / risk[["0"]]), se_log_rr = sqrt(sum(1 / events) - sum(1 / people)), rd = risk[["1"]] - risk[["0"]], se_rd = sqrt(sum(risk * (1 - risk) / people)) ))}cat(sprintf("%-14s %-5s %-7s %-17s %s\n", "Stratum", "Drug", "Placebo", "Risk ratio", "Risk difference"))cat(sprintf("%-14s %.3f %.3f %.2f [%.2f, %.2f] %.3f [%.3f, %.3f]\n", c("Lower baseline", "High baseline"), strata$drug, strata$placebo, exp(strata$log_rr), exp(strata$log_rr - z * strata$se_log_rr), exp(strata$log_rr + z * strata$se_log_rr), strata$rd, strata$rd - z * strata$se_rd, strata$rd + z * strata$se_rd), sep = "")log_ratio <- diff(strata$log_rr)se_ratio <- sqrt(sum(strata$se_log_rr^2))gap <- diff(strata$rd)se_gap <- sqrt(sum(strata$se_rd^2))cat(sprintf("Ratio of the risk ratios %.2f [%.2f, %.2f], truth 1\n", exp(log_ratio), exp(log_ratio - z * se_ratio), exp(log_ratio + z * se_ratio)))cat(sprintf("Difference of the risk differences %.3f [%.3f, %.3f], %s\n", gap, gap - z * se_gap, gap + z * se_gap, "truth -0.088"))Stratum Drug Placebo Risk ratio Risk differenceLower baseline 0.049 0.082 0.60 [0.44, 0.82] -0.033 [-0.053, -0.013]High baseline 0.184 0.301 0.61 [0.51, 0.73] -0.117 [-0.158, -0.075]Ratio of the risk ratios 1.02 [0.71, 1.46], truth 1Difference of the risk differences -0.084 [-0.130, -0.038], truth -0.088z = stats.norm.ppf(0.975)rows = []for stratum in (lower, high): arms = stratum.groupby("treated")["cv_event"].agg(["sum", "count"]) risk = arms["sum"] / arms["count"] rows.append({ "drug": risk[1], "placebo": risk[0], "log_rr": np.log(risk[1] / risk[0]), "se_log_rr": np.sqrt((1 / arms["sum"]).sum() - (1 / arms["count"]).sum()), "rd": risk[1] - risk[0], "se_rd": np.sqrt((risk * (1 - risk) / arms["count"]).sum())})strata = pd.DataFrame(rows, index=["Lower baseline", "High baseline"])print(f"{'Stratum':<14} {'Drug':<5} {'Placebo':<7} {'Risk ratio':<17} " "Risk difference")for name, row in strata.iterrows(): rr_limits = np.exp(row["log_rr"] + np.array([-z, z]) * row["se_log_rr"]) rd_limits = row["rd"] + np.array([-z, z]) * row["se_rd"] print(f"{name:<14} {row['drug']:.3f} {row['placebo']:.3f} " f"{np.exp(row['log_rr']):.2f} [{rr_limits[0]:.2f}, " f"{rr_limits[1]:.2f}] {row['rd']:.3f} [{rd_limits[0]:.3f}, " f"{rd_limits[1]:.3f}]")log_ratio = strata["log_rr"].iloc[1] - strata["log_rr"].iloc[0]se_ratio = np.sqrt((strata["se_log_rr"] ** 2).sum())gap = strata["rd"].iloc[1] - strata["rd"].iloc[0]se_gap = np.sqrt((strata["se_rd"] ** 2).sum())print(f"Ratio of the risk ratios {np.exp(log_ratio):.2f} " f"[{np.exp(log_ratio - z * se_ratio):.2f}, " f"{np.exp(log_ratio + z * se_ratio):.2f}], truth 1")print(f"Difference of the risk differences {gap:.3f} " f"[{gap - z * se_gap:.3f}, {gap + z * se_gap:.3f}], truth -0.088")Stratum Drug Placebo Risk ratio Risk differenceLower baseline 0.049 0.082 0.60 [0.44, 0.82] -0.033 [-0.053, -0.013]High baseline 0.184 0.301 0.61 [0.51, 0.73] -0.117 [-0.158, -0.075]Ratio of the risk ratios 1.02 [0.71, 1.46], truth 1Difference of the risk differences -0.084 [-0.130, -0.038], truth -0.088The risk ratio is 0.60 (0.44 to 0.82) with a lower baseline and 0.61 (0.51 to 0.73) with a high baseline. Their ratio is 1.02, close to the true 1, although its interval from 0.71 to 1.46 would also fit a real difference. The risk differences are −0.033 and −0.117, and the gap between them is −0.084, with an interval from −0.130 to −0.038 that excludes zero. On the difference scale baseline pressure modifies the effect, and on the ratio scale it does not. Both statements describe the same 4,000 patients.
Arithmetic ties the two scales together. When the risks on placebo differ and the treatment has an effect, equal risk ratios force unequal risk differences, and equal risk differences force unequal risk ratios. So “no interaction” is an incomplete statement until it names the scale, and the absence of a product term in a log-linear model says nothing about equal benefit in absolute terms. A logistic model works on a third scale, the odds ratio, and gives its own answer.
For a decision about whom to treat, the difference scale counts the events: 1 / 0.033 gives one event prevented for about every 30 patients treated with a lower baseline, and 1 / 0.117 gives one for about every 9 with a high baseline. Report the risks in each stratum with both measures, and say on which scale a product term was fitted. The risk measures page gives the same advice for any ratio.
Mistakes to avoid
Section titled “Mistakes to avoid”Do not choose covariates by a p-value or by a change in the estimate. BMI changed the activity coefficient by 47% with p = 3e-90, admission changed it by 34% with p = 3.7e-49, and each moved the estimate away from the true −6. Choose the adjustment set from the diagram, before the outcome model is fitted.
Do not adjust for a variable measured after the exposure began until the diagram says what it is. BMI and admission were both recorded after enrollment. One is a mediator and one is a collider, and the model with all four covariates returned −1.58 where the truth is −6. A covariate fixed before the exposure cannot be a mediator, which is why the propensity scores page keeps its model to covariates that precede the treatment decision.
Do not recruit or restrict on a common consequence of the exposure and the outcome. Among admitted patients asthma appeared to lower blood pressure by 4.88 mm Hg, and its true effect is zero.
Do not treat a passed independence check as proof of the diagram. The hidden cause habits left all seven implied independencies in place and removed every valid adjustment set.
Do not report the coefficient of a confounder as its effect. Age had a coefficient of 0.48 in the adjusted model and 0.59 in a model of its own, and the adjusted model was built for neither question.
Do not read a product term on one scale as biology. The drug multiplied the risk by about 0.6 in both strata, a ratio of risk ratios of 1.02, and the same patients gave a difference of risk differences of −0.084. Whether an interaction appeared depended on the scale, while the drug did the same thing in both analyses.
Scientific references
Section titled “Scientific references”Textor and colleagues, 2016 describe the dagitty package for causal inference with directed acyclic graphs in R.
Greenland, Pearl, and Robins, 1999 describe causal diagrams for epidemiologic research.
Hernán, Hernández-Díaz, and Robins, 2004 describe a structural approach to selection bias.
Westreich and Greenland, 2013 describe the Table 2 fallacy in presenting and interpreting confounder and modifier coefficients.
VanderWeele and Knol, 2014 give a tutorial on interaction on the additive and the multiplicative scale and on how to present an interaction analysis.
Further reading
Section titled “Further reading”The DAGitty learning page links the manual, a tutorial on covariate roles such as confounder and mediator, and an introduction to d-separation.
The ggdag documentation shows the plotting functions of the package for adjustment sets, paths and colliders, such as ggdag_adjustment_set() and ggdag_paths().
The networkx reference for d-separation documents is_d_separator(), find_minimal_d_separator() and is_minimal_d_separator().
Causal Inference: What If by Hernán and Robins has chapters on effect modification, causal diagrams, confounding and selection bias.
The g-computation page takes an outcome model with a chosen adjustment set and standardizes it to a population effect. The propensity scores page adjusts for many measured confounders at once through the exposure model.