HSCI 410 · Lesson 3

Linear & Logistic Regression

Exploratory Data Analysis For Epidemiology

Learning objectives for this lesson:

  • Identify when least squares regression is the appropriate tool for a continuous outcome, construct a linear model that controls confounding and identifies interaction, and interpret regression coefficients from both technical and causal perspectives
  • Use the ANOVA decomposition, F-tests, t-tests, and R² to assess a linear model and its coefficients; convert nominal, ordinal, or continuous predictors into indicator variables; assess linearity, homoscedasticity, and normality of residuals; and detect and address collinearity
  • Explain why linear regression cannot be used for dichotomous outcomes, understand log odds as a measure of disease and how they relate to a linear combination of predictors, and build and interpret logistic regression models
  • Compute and interpret odds ratios derived from a logistic regression model, and assess confounding and interaction on the logit scale
  • Evaluate logistic regression models using likelihood-ratio and Wald tests, goodness-of-fit tests, ROC curves, and residual analysis
  • Understand how linear and logistic regression fit in the family of generalised linear models, and fit exact and conditional logistic regression models for sparse and matched data
  • Develop a full (maximal) model incorporating biological understanding of the system under study, distinguishing prediction from causal explanation and letting a causal diagram decide what to adjust for
  • Carry out procedures to reduce a large number of predictors to a manageable subset, and address the functional form of continuous predictors and the handling of missing values
  • Build regression-type models using both statistical and non-statistical criteria, specify interaction terms in advance, and choose among model-selection criteria (adjusted R², AIC, BIC, cross-validation)
  • Evaluate the reliability of a regression-type model and present the results from an analysis in a meaningful way

This course was developed by Dr. Kiffer G. Card, Faculty of Health Sciences, Simon Fraser University based on Dohoo, I. R., Martin, S. W., & Stryhn, H. (2012). Methods in Epidemiologic Research. VER Inc.

Reference

Glossary: Key Terms, People & Concepts

📚 Reference page, available throughout the lesson

This glossary collects the key concepts, people, and ideas you will meet in this lesson. Use it as a reference while you work through the material, or as a review before assessments. Type in the search box to filter entries.

Key Concepts & Ideas
Linear Regression A model that expresses a continuous outcome as a linear combination of predictors plus error. The workhorse method for relating Y to one or more X's when Y is roughly continuous.
Simple Linear Regression A linear regression with a single predictor: Y = β₀ + β₁X + ε. Fits a line through the data minimizing squared residuals.
Multiple Regression Linear regression with two or more predictors. Each β is interpreted as the change in Y per unit change in that predictor, holding the others constant.
Intercept (β₀) The expected value of Y when all predictors equal zero. Often without a sensible interpretation if zero is outside the data range; centering predictors helps.
Beta Coefficient (Slope) A regression coefficient (β) representing the expected change in the outcome per one-unit increase in that predictor, with other predictors held fixed.
Residual The difference between an observed Y and the value predicted by the model (Y − Ŷ). Patterns in residuals diagnose model misspecification.
R² (Coefficient of Determination) The proportion of variance in the outcome explained by the model, ranging from 0 to 1. Adjusted R² penalises adding predictors.
Interaction (Effect Modification) A situation where the effect of one predictor on Y depends on the level of another. Modeled by including a product term (X₁ × X₂) in the regression.
Dummy / Indicator Variable A 0/1 variable used to encode a categorical predictor in a regression. A k-level factor needs k−1 dummies plus a reference category.
Methods & Statistical Concepts
OLS (Ordinary Least Squares) The estimation method for linear regression that finds β's minimizing the sum of squared residuals. Best Linear Unbiased Estimator (BLUE) under the Gauss-Markov assumptions (Stigler, 1981).
Homoscedasticity Constant variance of residuals across the range of fitted values. Violated when residual spread fans out (heteroscedasticity); biases standard errors (White, 1980).
Normality of Residuals The assumption that residuals are normally distributed. Required for valid t- and F-tests in small samples; checked via Q-Q plots.
Independence of Errors The assumption that residuals are uncorrelated. Violated by clustered or time-series data; addressed with mixed models or GEE.
Leverage A measure of how unusual a data point's predictor values are. High-leverage points have the potential to strongly influence fitted coefficients.
Cook's Distance A diagnostic combining leverage and residual to flag observations whose deletion materially changes the fitted regression. Values > 1 (or > 4/n) warrant investigation (Cook, 1977).
Multicollinearity High correlation among predictors, which inflates standard errors and destabilises coefficient estimates. Diagnosed with VIF.
VIF (Variance Inflation Factor) A diagnostic for multicollinearity: VIF > 5–10 signals problematic correlation between a predictor and the others.
Standard Error of β The estimated standard deviation of a regression coefficient. Used to form confidence intervals (β ± 1.96·SE) and t-statistics for significance testing.
F-test (Overall Model) A test of the joint null that all slopes equal zero. Reported in the ANOVA table; significance indicates the model explains variance better than the mean alone.
Key People
Francis Galton (1822–1911) English polymath who introduced the concept of regression (“regression toward the mean”) while studying inheritance of stature in parents and children. See the Francis Galton entry for detail.
Karl Pearson (1857–1936) English statistician who formalised the correlation coefficient (Pearson's r) and many of the foundations of regression and biometrics.
Ronald A. Fisher (1890–1962) British statistician who developed maximum likelihood estimation, ANOVA, and the F-test, and unified linear models within the analysis of variance framework.
Key Concepts & Ideas
Binary Outcome An outcome variable taking only two values (e.g., diseased/healthy, yes/no, 1/0). The natural target of logistic regression.
Probability (p) The chance an event occurs, ranging from 0 to 1. Logistic regression models the probability of the outcome as a function of predictors.
Odds The ratio of the probability of the event to its complement: p / (1−p). Ranges from 0 to infinity. Multiplicative in nature, easy to compare across groups.
Log Odds (Logit) The natural logarithm of the odds: logit(p) = log(p/(1−p)). Ranges from −∞ to +∞; the linear scale on which logistic regression is fit.
Odds Ratio (OR) The ratio of odds in two groups. The exponentiated logistic regression coefficient: OR = exp(β). OR > 1 indicates higher odds; OR < 1 lower.
Separation When a predictor (or combination) perfectly classifies the outcome, the maximum likelihood estimate diverges to infinity. Solutions include exact logistic regression or penalised likelihood (Firth).
Conditional Logistic Regression A logistic model for matched-pair or matched-set data. Conditions on the matched-set totals, eliminating matching variables from the likelihood.
Outcome Prevalence The proportion of cases in the dataset. Affects intercept interpretation and influences whether OR approximates RR (close only when outcome is rare).
Methods & Statistical Concepts
Logit Link Function The link function in logistic regression: g(p) = log(p/(1−p)). Maps probabilities (0,1) onto the real line so a linear model can be fit.
Generalised Linear Model (GLM) A unified framework (McCullagh & Nelder, 1989) extending linear regression to any exponential-family distribution via a link function. Logistic, Poisson, and linear regression are all GLMs.
Maximum Likelihood Estimation (MLE) An estimation method that picks parameter values maximising the likelihood of observing the data. The standard approach for fitting logistic regression.
Deviance −2 times the log-likelihood, used as the GLM analogue of the residual sum of squares. Differences in deviance between nested models follow a χ².
Wald Test A test of a coefficient using (β/SE)² ~ χ²₁. Standard in regression output but unreliable when SE is very large (e.g., separation).
Hosmer-Lemeshow Test A goodness-of-fit test grouping observations into deciles of predicted probability and comparing observed to expected counts. Sensitive to group choice and sample size.
ROC Curve A plot of sensitivity against 1 − specificity across all classification thresholds. Summarises a model's discriminative ability.
AUC / C-Statistic Area under the ROC curve. AUC = 0.5 means no discrimination; 1.0 means perfect. Often used to compare predictive models.
Pseudo-R² Various analogues of linear-regression R² for GLMs (e.g., McFadden's, Cox-Snell, Nagelkerke). Should not be interpreted as proportion of variance explained.
Exact Logistic Regression An estimation method based on conditional permutation distributions, useful with small samples or sparse data where MLE fails or is biased.
Firth's Penalised Likelihood A bias-reducing modification to MLE that yields finite estimates under separation, often preferred over exact methods for moderate samples.
Key People
David R. Cox (1924–2022) British statistician who introduced logistic regression as a tool for binary data (1958) and later the proportional hazards (Cox) model for survival analysis.
McCullagh & Nelder Peter McCullagh (1952– ) and John Nelder (1924–2010), British statisticians whose 1983/1989 textbook formalised the unified theory of generalised linear models.
Hosmer & Lemeshow David Hosmer and Stanley Lemeshow, American biostatisticians whose textbook Applied Logistic Regression standardised practice including the goodness-of-fit test and purposeful model selection.
Key Concepts & Ideas
Model Building The iterative process of choosing predictors, interactions, and functional forms for a regression model. Should be guided by the research question, prior knowledge, and DAGs, not by data dredging.
Parsimony The principle that, all else equal, simpler models are preferred over more complex ones. Parsimonious models tend to generalise better to new data.
Overfitting When a model captures noise as if it were signal, performing well on the training data but poorly on new observations. Mitigated by parsimony, regularisation, and cross-validation.
Underfitting When a model is too simple to capture the systematic structure of the data, leading to high bias.
Confounding Mixing of effects between an exposure and an extraneous variable that is associated with both exposure and outcome. Adjusting for confounders is a primary motivation for multivariable models.
Mediator A variable on the causal pathway between exposure and outcome. Adjusting for a mediator removes part of the total effect, which is usually undesirable when estimating a total effect.
Effect Modifier A variable across whose levels the effect of the exposure on the outcome differs. Modeled with an interaction term; reported by stratum rather than collapsed.
Hierarchical Well-Formulated Model A model that includes all lower-order terms implied by any included higher-order term (e.g., if X₁X₂ is in the model, both X₁ and X₂ should be).
Methods & Statistical Concepts
Forward Selection A stepwise procedure that starts with no predictors and adds them one at a time, selecting whichever improves a chosen criterion (e.g., AIC, p-value) the most until none qualify.
Backward Elimination A stepwise procedure that starts with all candidate predictors and removes them one at a time, dropping whichever's removal improves the criterion until none can be dropped.
Stepwise Selection A combination of forward and backward steps. Widely used historically but criticised for inflated Type I error, biased coefficients, and irreproducibility.
AIC (Akaike Information Criterion) A model-fit criterion: AIC = −2·log-likelihood + 2k. Lower is better. Balances fit against complexity; favors models that generalise (Akaike, 1974).
BIC (Bayesian Information Criterion) Like AIC but with a stiffer penalty for complexity: BIC = −2·log-likelihood + k·log(n). Tends to select more parsimonious models than AIC (Schwarz, 1978).
Likelihood Ratio Test (LRT) A test comparing two nested models via −2·log(L₀/L₁), which follows a χ² distribution under the null. Used to test whether added terms improve fit.
Change-in-Estimate A confounder-selection rule: include a variable if its addition changes the exposure coefficient by more than a threshold (often 10%). Less arbitrary than p-value selection.
Cross-Validation A resampling procedure (e.g., k-fold) that holds out part of the data, fits the model on the rest, and measures performance on the held-out subset. Estimates out-of-sample error.
Lasso Regression A penalised regression that adds an L1 penalty on coefficient magnitudes, shrinking some coefficients to exactly zero. Performs variable selection automatically (Tibshirani, 1996).
Ridge Regression A penalised regression with an L2 penalty on coefficient magnitudes. Shrinks coefficients toward zero (but not exactly to zero); helpful with multicollinearity.
Elastic Net A penalised regression combining L1 (lasso) and L2 (ridge) penalties. Balances variable selection with stability when predictors are correlated.
Purposeful Selection A model-building strategy (Hosmer-Lemeshow) combining substantive theory, screening, change-in-estimate checks, and assessment of confounding/interaction.
Key People
Hirotugu Akaike (1927–2009) Japanese statistician who introduced the Akaike Information Criterion (AIC) in 1973, providing an information-theoretic basis for model selection (Akaike, 1974).
Robert Tibshirani (1956– ) Canadian statistician who introduced the lasso (Tibshirani, 1996) and co-authored landmark texts on statistical learning. A leading figure in modern regularised regression.
No matching entries. Try a different search term.
Section 1 of 13

Introduction & Regression Analysis

⏱ Estimated time: 15 minutes
Lesson 3 · Part 1 · HSCI 410

Linear Regression

The workhorse model for continuous outcomes, built from first principles to causal reading.

Why this model

From categorical to continuous outcomes

Linear regression models a continuous outcome as a weighted sum of predictors plus a normally distributed error. Ordinary least squares finds the best-fitting coefficients.

The simple model
\[ \color{#0B7B6B}{Y} = \color{#C2410C}{\beta_0} + \color{#6D28D9}{\beta_1} \color{#1D4ED8}{X_1} + \color{#BE185D}{\varepsilon} \]
Y outcome β₀ intercept β₁ slope X₁ predictor ε error
The applied context

Formulas grounded in a real dataset

The R activity uses the cleaned survey data from an earlier lesson. Throughout, the running example is a multivariable model for systolic blood pressure with age, BMI, depression score, smoking, and physical activity as predictors.

  • Each formula in the narration corresponds to something you can fit in R.
  • The diagnostics in a later section are checks you will run on your own model output.
  • No need to run R now. The written lesson has the full annotated code below.
Section 1 of 4

Introduction & Regression Analysis

The simple and multivariable models, and what their coefficients actually mean.

The simple model

Three components, one equation

Simple linear regression (Eq 14.1)
\[ \color{#0B7B6B}{Y} = \color{#C2410C}{\beta_0} + \color{#6D28D9}{\beta_1} \color{#1D4ED8}{X_1} + \color{#BE185D}{\varepsilon}, \quad \color{#BE185D}{\varepsilon} \sim N(0,\,\sigma^2) \]
Y outcome β₀ intercept β₁ slope X₁ predictor ε error, normal mean 0

\(\beta_0\)

Intercept: predicted Y when X is 0.

\(\beta_1\)

Slope: change in Y per one-unit increase in X.

\(\varepsilon\)

Error: normal with mean 0, constant variance sigma-squared.

Least squares

Minimizing the sum of squared residuals

OLS objective
\[ \color{#0B7B6B}{\hat{\boldsymbol{\beta}}} = \underset{\boldsymbol{\beta}}{\arg\min} \sum_{i=1}^{n} \left(\color{#C2410C}{Y_i} - \color{#6D28D9}{\hat{Y}_i}\right)^2 \]
β̂ fitted coefficients Yᵢ observed value Ŷᵢ predicted value
Red segments = residuals. OLS minimizes their total squared length.
The multivariable model

Each coefficient is an adjusted estimate

Multivariable linear regression (Eq 14.3)
\[ \color{#0B7B6B}{Y} = \color{#C2410C}{\beta_0} + \color{#6D28D9}{\beta_1} \color{#1D4ED8}{X_1} + \color{#6D28D9}{\beta_2} \color{#1D4ED8}{X_2} + \cdots + \color{#BE185D}{\varepsilon} \]
Y outcome β₀ intercept βⱼ slope for predictor j Xⱼ predictor j ε error

\(\beta_1\) estimates the effect of \(X_1\) on \(Y\) holding \(X_2, \ldots, X_k\) constant.

The betas are not biased by any variable included in the equation, but they can be biased if confounders are omitted from the model.Dohoo, Martin & Stryhn, 2012
Two cautions

Terminology and model parsimony

Terminology

Multivariable: more than one predictor. Multivariate: more than one outcome. In epidemiology, almost every regression model is multivariable.

Parsimony

Including unnecessary predictors inflates estimation error and reduces performance on new data. Include all important confounders; remove variables that add nothing.

Carry forward

What to take into the next section

  • \(\beta_1\) is a slope: the expected change in \(Y\) per one-unit increase in \(X_1\).
  • In a multivariable model, every \(\beta\) is an adjusted estimate holding other predictors constant.
  • Predictive association and causation are different things. A later section handles the distinction explicitly.

Introduction and Overview

Earlier lessons produced a clean, descriptive view of the data. This lesson takes the next step from description to inference: linear regression is the workhorse model for explaining or predicting a continuous outcome from one or more predictors, fit by ordinary least squares (Stigler, 1981). Across four content sections we walk through this in order: the simple and multivariable model and what its coefficients mean (this section), the ANOVA decomposition and how to test the model and its individual coefficients (a later section), how to handle different types of predictor variables and detect collinearity (a later section), and how to detect and model interactions and give a regression a defensible causal interpretation (a later section). Model diagnostics, the residual and influence checks that show whether the fit can be trusted, run alongside the R work throughout.

Learning Objectives

  • State when linear regression is the appropriate modelling choice for a public-health outcome.
  • Write down and interpret the simple linear regression equation, including the intercept and slope.
  • Extend the simple model to a multivariable model and explain what each coefficient now represents.
  • Distinguish predictive from causal interpretations of regression coefficients.

Why Linear Regression?

Up to this point, most examples of relating an outcome to an exposure have been based on qualitative outcome variables, that is, variables that are categorical or dichotomous. Linear regression is suitable for modelling the outcome when it is measured on a continuous or near-continuous scale. Examples include birth weight, blood pressure, body mass index, and disease frequency at a regional level.

Key Concept

In regression analysis, the relationship between the outcome and the predictors is asymmetric: we think the value of the outcome is caused by (or we wish to predict it by) the value of another variable (the predictor). Using X-variables to predict Y does not necessarily imply causation; we might just be estimating predictive associations.

The Simple Regression Model

When only one predictor variable is used, the model is called a simple regression model. The term “model” denotes the formal statistical formula that describes the relationship between the predictor and the outcome.

▸ INTERACTIVE STORY: THE BEST-FIT TUG OF WAR Open full screen ↗

Springs, residuals, and the line that minimizes them. Next ▶ advances scenes.

A 6-scene visualization of OLS: scattered observations, a wobbling candidate line, residuals as physical springs, and the line settling into the unique position that minimizes the sum of squared errors.

Simple linear regression (Eq 14.1)
\[ \color{#0B7B6B}{Y} = \color{#C2410C}{\beta_0} + \color{#6D28D9}{\beta_1} \color{#1D4ED8}{X_1} + \color{#BE185D}{\varepsilon} \]
The outcome equals the intercept plus the slope times the predictor, plus the error term.

In this equation, β0 is the intercept (or constant), β1 is the regression coefficient, and ε is the error term. The errors are assumed to be normally and independently distributed (ε ~ N(0, σ²)). We estimate these errors by residuals, the difference between the observed value and the value predicted by the model.

Reading a coefficient in plain words

Suppose the outcome Y is systolic blood pressure in mmHg and the predictor X1 is age in years, and the fitted line is Ŷ = 100 + 0.5 × age. The intercept of 100 is the model’s predicted blood pressure at age 0, which is only a mathematical anchor rather than a real value for a newborn. The slope of 0.5 is usually the part you care about: comparing two people whose ages differ by one year, the model predicts the older one has, on average, a systolic blood pressure about 0.5 mmHg higher, roughly 20 mmHg across a 40-year span. Read it as a comparison of averages between groups that differ in the predictor; it does not by itself describe what happens inside any one person over time.

Intercept (β0)Click to explore
Regression Coefficient (β1)Click to explore
Error Term (ε)Click to explore

✏ Interactive: OLS Line-of-Best-Fit Sandbox

Click anywhere on the chart to add a point. Click on an existing point to remove it. The least-squares line, residuals, R², and standard error of the slope update live. Add an extreme outlier and watch one observation drag the entire line (Cook, 1977; Belsley, Kuh, & Welsch, 1980).

n
0
Slope (β̂)
Intercept (α̂)
SE(β̂)
RMSE
Sum sq. resid.
t-stat
Try this: load a random sample, then click "Add an outlier" to drop a point at (10, 1). One leverage point can pull the slope by half a unit, the visible reason why diagnostic plots, influence statistics, and robust estimators matter (Huber, 1964; Cook, 1977).
Two residual-versus-fitted plots: on the left an even horizontal band (homoscedastic); on the right a fan that widens with the fitted value (heteroscedastic).
A residuals-versus-fitted plot is the standard check for constant variance. An even band (left) supports homoscedasticity; a widening fan (right) signals heteroscedasticity, which leaves coefficients unbiased but distorts their standard errors.

The Multivariable Model

Almost without exception, the regression models used by epidemiologists will contain more than one predictor variable. These are known as multiple regression or multivariable models.

Terminology Note

Multivariate indicates 2 or more outcome variables; multivariable denotes more than 1 predictor. In epidemiology, we almost always mean multivariable models.

Multivariable linear regression (Eq 14.3)
\[ \color{#0B7B6B}{Y} = \color{#C2410C}{\beta_0} + \color{#6D28D9}{\beta_1} \color{#1D4ED8}{X_1} + \color{#6D28D9}{\beta_2} \color{#1D4ED8}{X_2} + \color{#BE185D}{\varepsilon} \]
The outcome equals the intercept plus each slope times its predictor, summed over all predictors, plus the error.

A major difference from simple regression is that in the multivariable model, β1 is an estimate of the effect of X1 on Y after controlling for the effects of X2. This is the key advantage of multivariable analysis: it accounts for confounding by extraneous variables.

Why use multivariable models?

In observational studies, incorporating more than one predictor almost always leads to a more complete understanding of how the outcome varies, and it decreases the chance that the regression coefficients for exposures of interest are biased by confounding variables. The βs are not biased by any variable included in the equation, but they can be biased if confounding variables are omitted from the equation.

Confounders vs intervening variables

Assuming we have not included intervening variables or effects of the outcome in our model, the βs are not confounded by any variable in the regression equation. However, from a causal perspective, if intervening variables are included, the coefficients do not estimate the causal effect. One can never be sure that there are no important unmeasured confounders that were omitted from the model.

Trade-offs in model building

A major trade-off in model-building is to avoid omitting necessary confounding variables while not including variables of little importance. Including too many unimportant variables increases the number of βs estimated and may lead to poor performance of the equation on future datasets. Also, having to measure unnecessary variables increases the cost of future work.

R Activity: correlation and a first multivariable linear model

Picking up the cleaned phaa_survey_clean.csv from an earlier lesson, we will (1) test bivariate correlations, (2) inspect a correlation matrix for the numeric variables we plan to include in a model, and (3) fit a multivariable linear regression for systolic BP. The full annotated script is in r-activities/HSCI_410_Lesson_3_Linear_Regression.R.

# 0. Load the cleaned data + packages we will use ---------------------------
library(corrplot);  library(regclass);  library(caret)
phaa <- read.csv("phaa_survey_clean.csv", stringsAsFactors = FALSE)

# 1. Bivariate correlation between two numeric variables --------------------
cor.test(phaa$age, phaa$systolic_bp,
         method = "pearson")

# 2. Correlation matrix + visual --------------------------------------------
keep_num <- c("age", "bmi", "systolic_bp", "diastolic_bp",
              "phys_act_min", "discrimination_score",
              "social_support_score", "dep_score", "anx_score")
cor_mat <- cor(phaa[, keep_num], use = "complete.obs")
round(cor_mat, 2)
corrplot(cor_mat, method = "color", type = "upper",
         addCoef.col = "black", tl.col = "black", tl.srt = 45)

# 3. Set the reference level on a factor before fitting lm() ----------------
phaa$gender <- as.factor(phaa$gender)
phaa$gender <- relevel(phaa$gender, ref = "Woman")

# 4. Multivariable linear model for systolic BP -----------------------------
model_3 <- lm(systolic_bp ~ age + gender + smoker + bmi
                          + dep_score + phys_act_min,
              data = phaa)
summary(model_3)
confint(model_3)

# 5. Diagnostics: linearity, equal variance, normal residuals, outliers -----
par(mfrow = c(2, 2));  plot(model_3);  par(mfrow = c(1, 1))
VIF(model_3)            # multicollinearity
varImp(model_3)         # variable importance

How to read the output. Each coefficient in summary(model_3) is the average change in systolic BP per one-unit increase in that predictor, holding the other predictors constant. The (Intercept) is the predicted BP when every numeric predictor is 0 and every factor is at its reference level, which is not always meaningful, which is why we centre age in a later lesson. VIF values > 5 mean two predictors are carrying mostly the same information.

R Reflect on what you just ran

Use the questions below to interpret the output you produced. Look at your console / plot before answering.

1. From cor.test(phaa$age, phaa$systolic_bp), what is the Pearson r and its 95% CI? Does the CI exclude zero? Translate the magnitude into plain English (small / moderate / strong).

Model answerPearson r is around 0.30–0.35, 95% CI roughly (0.22, 0.41), clearly excluding zero. The magnitude is small-to-moderate by Cohen's benchmarks (small ~0.1, moderate ~0.3, strong ~0.5+), a real but modest age-BP relationship. The CI excluding zero plus a non-trivial effect size means age explains some of the variation in BP, but most of it (about 90% of the variance) is attributable to other factors.

2. In summary(model_3), what is the coefficient on age and its p-value? In one sentence, state the adjusted association of age and systolic BP, and whether the 95% CI from confint() excludes zero.

Model answersummary(model_3) typically shows an age coefficient of ~0.5 mmHg per year (range 0.3–0.7 depending on covariate inclusion) with p < 0.001 in a sample of n > 500. The 95% CI from confint() excludes zero. Adjusted association: each additional year of age is associated with roughly 0.5 mmHg higher systolic BP, after accounting for sex, BMI, and smoking. The effect compounds over age decades, explaining the ~15–20 mmHg average rise from age 30 to 70.

3. Look at VIF(model_3). Which predictor has the highest VIF? Is it above 5 or 10? If you removed it, how would you expect the SE on a correlated predictor to change?

Model answerVIF(model_3) typically shows the highest VIF for one of the BP-related variables or BMI, usually around 2–3, below the conventional 5/10 thresholds. If a predictor with VIF > 5 were removed, the SE on its correlated counterpart would drop noticeably (typically by 15–30%), and the point estimate would shift slightly as the model re-attributes shared variance. Multicollinearity doesn't bias coefficients, but inflates their SEs and CIs, making true effects appear non-significant.
Saved.
Knowledge check: this section

1. What type of outcome variable is linear regression most suitable for?

Linear regression is suitable for modelling the outcome when it is measured on a continuous or near-continuous scale, such as birth weight, blood pressure, or body mass index.

2. In the equation Y = β0 + β1X1 + ε, what does β1 represent?

β1 is the regression coefficient that describes how the mean value of Y changes for each one-unit increase in X1. The intercept (β0) is the value of Y when X1 = 0.

3. What is the key advantage of a multivariable regression model over a simple regression model?

The key advantage is that each β coefficient estimates the effect of its predictor after controlling for all other variables in the model, thereby reducing bias from confounding variables.

Reflection

Think of a continuous outcome variable in your field of interest. What predictors would you include in a regression model? How would you decide which variables are confounders versus intervening variables?

Model answerPick an outcome (e.g., HbA1c in adults with type-2 diabetes). Predictors: age, sex, BMI, physical activity, dietary patterns, medication adherence, sleep duration, depression score, SES. Confounders vs. intervening variables: confounders are causes of both exposure and outcome that exist before the exposure (age, SES, family history); intervening variables are on the causal pathway from exposure to outcome (medication adherence is between treatment intensity and HbA1c). The distinction is decided by a DAG, not by statistical tests: if a variable is a mediator and you want the total effect of an exposure, do NOT adjust for it (otherwise you block part of the causal path you're trying to estimate). If you want the direct effect, DO adjust. Pre-registering the DAG and the adjustment set prevents post hoc rationalisation.
Reflection saved!
* Complete the quiz and reflection to continue.
Section 2 of 13

Hypothesis Testing & Effect Estimation

⏱ Estimated time: 20 minutes
Section 2 of 4

Hypothesis Testing & Effect Estimation

ANOVA decomposition, the overall F-test, individual t-tests, and the coefficient of determination.

The ANOVA decomposition

Partitioning total variation in Y

Sums of squares identity
\[ \underbrace{\sum(Y_i - \bar{Y})^2}_{\color{#0B7B6B}{\text{SST}}} = \underbrace{\sum(\hat{Y}_i - \bar{Y})^2}_{\color{#C2410C}{\text{SSM}}} + \underbrace{\sum(Y_i - \hat{Y}_i)^2}_{\color{#6D28D9}{\text{SSE}}} \]
SST total variation SSM explained by model SSE residual (unexplained)

SSM

Model sum of squares. Variation explained by predictors. Degrees of freedom = k.

SSE

Error sum of squares. Residual variation. Degrees of freedom = n minus (k + 1).

SST

Total sum of squares. Degrees of freedom = n minus 1.

The F-test

Overall model significance

Overall F-statistic
\[ \color{#0B7B6B}{F} = \frac{\color{#C2410C}{\text{MSM}}}{\color{#6D28D9}{\text{MSE}}} = \frac{\text{SSM}/k}{\text{SSE}/(n-k-1)} \]
F overall F-ratio MSM mean square, model MSE mean square, error

Null hypothesis: \(H_0: \beta_1 = \beta_2 = \cdots = \beta_k = 0\).

Example 14.1: birth weight on gestation length (n = 5,000). F(1, 4998) = 1,790, p < 0.0001, R² = 0.26. Each additional week of gestation adds about 124.5 grams of birth weight (95 percent CI: 118.7 to 130.3).Dohoo et al., 2012
Individual coefficients

The t-test for each slope

t-statistic for \(\hat{\beta}_j\) (Eq 14.6)
\[ \color{#0B7B6B}{t} = \frac{\color{#C2410C}{\hat{\beta}_j} - \color{#6D28D9}{\beta^*}}{\color{#1D4ED8}{\text{SE}(\hat{\beta}_j)}}, \quad df = n - (k+1) \]
t t-statistic β̂ⱼ estimated coefficient β* null value (usually 0) SE standard error
95 percent confidence interval
\[ \color{#C2410C}{\hat{\beta}_j} \;\pm\; \color{#6D28D9}{t_{0.025}} \cdot \color{#1D4ED8}{\text{SE}(\hat{\beta}_j)} \]
β̂ⱼ estimated coefficient t₀.₀₂₅ critical t-value SE standard error

A non-significant result means insufficient precision to distinguish the effect from zero, not that the effect is zero. Prediction intervals for new observations are wider than confidence intervals, and widen away from the mean of X.

Model fit

R-squared and adjusted R-squared

Coefficient of determination
\[ \color{#0B7B6B}{R^2} = \frac{\color{#C2410C}{\text{SSM}}}{\color{#1D4ED8}{\text{SST}}} = 1 - \frac{\color{#6D28D9}{\text{SSE}}}{\color{#1D4ED8}{\text{SST}}} \]
proportion of variance explained SSM model sum of squares SSE error sum of squares SST total sum of squares
Adjusted R-squared
\[ \color{#0B7B6B}{R^2_{\text{adj}}} = 1 - \frac{\color{#C2410C}{\text{MSE}}}{\color{#1D4ED8}{\text{MST}}} \]
R²₃ₐ₌ adjusted for predictors MSE mean square error MST mean square total

R² always rises

Adding any variable increases R², regardless of whether it contains useful information.

Adjusted R² can fall

Adding an uninformative variable increases the MSE relative to MST, so adjusted R² declines. Use it to compare models of different sizes; test groups of terms with a partial F-test.

Carry forward

Testing done; now predictor form

  • The F-test and t-tests quantify whether the model explains variation; R² quantifies how much.
  • In observational studies, variable selection methods that maximize F produce inflated significance. Report adjusted R² alongside R².
  • A significant overall model can still contain poorly coded predictors. A later section addresses that directly.

Introduction and Overview

An earlier section set up the regression model. This section turns to the question of whether the model is doing useful work: how much of the variation in the outcome does it actually explain, and which individual coefficients are meaningfully different from zero? The ANOVA decomposition and the formal tests of model significance are how those questions get answered.

Learning Objectives

  • Decompose the variability of Y using the ANOVA sums-of-squares table.
  • Use the overall F-test to assess whether a regression model explains useful variation.
  • Test individual coefficients with t-tests and report effect sizes with 95% confidence intervals.
  • Interpret R2 and adjusted R2 as measures of model fit, and recognise their limits.

The ANOVA Table

The idea behind regression is that information in the X-variables can be used to predict the value of Y. The formal way this is approached is to ascertain how much of the sums of squares (SS) of Y we can explain with knowledge of the X-variable(s).

SourceSums of SquaresdfMean SquareF-test
Model (regression)SSM = Σ(Ŷi − Ȳ)2dfM = kMSM = SSM/dfMMSM/MSE
Error (residual)SSE = Σ(Yi − Ŷi)2dfE = n−(k+1)MSE = SSE/dfE
TotalSST = Σ(Yi − Ȳ)2dfT = n−1MST = SST/dfT

Here, k is the number of predictor variables in the model (not counting the intercept). When the SS are divided by their degrees of freedom (df), the result is a mean square, denoted MSM (model), MSE (error), and MST (total). The MSE is our estimate of the error variance σ², and the square root of σ² is called the root MSE or the standard error of prediction.

Assessing the Significance of a Linear Regression Model

We use the F-test from the ANOVA table to assess whether the predictors collectively have a statistically significant relationship with the outcome. The null hypothesis is H0: β1 = β2 = … = βk = 0.

In plain terms, the overall F-test asks a single yes-or-no question: taken as a set, do the predictors track the outcome better than simply predicting its overall mean for everyone? If the answer is no, the F ratio sits near 1; a large F with a small p-value says the predictors are doing real work.

Example 14.1: Birth Weight on Gestation Length

A simple linear regression model with birth weight (-bwt-) as the outcome and gestation length (-gest-) as the sole predictor was fit using the bw5k dataset (n = 5,000).

Results: F(1, 4998) = 1,790.09, P < 0.0001, R² = 0.2637. The coefficient for -gest- is 124.5 gm per week (95% CI: 118.7–130.3), meaning for each additional week of gestation, birth weight increases by approximately 124.5 gm.

Testing Individual Regression Coefficients

A t-test with n−(k+1) degrees of freedom is used to evaluate the significance of any individual regression coefficient. The usual null hypothesis is H0: βj = 0.

t-test for a regression coefficient (Eq 14.6)
\[ \color{#0B7B6B}{t} = \frac{\color{#C2410C}{\hat{\beta}_j} - \color{#6D28D9}{\beta^*}}{\color{#1D4ED8}{\text{SE}(\hat{\beta}_j)}} \]
The t-statistic is the estimated coefficient minus its null value (usually 0), divided by the coefficient’s standard error.
Predictions & intervals

Two sources of uncertainty stack when you use a fitted model to predict. The first is uncertainty about where the regression line itself sits, captured by the usual standard error. The second is the natural scatter of an individual observation around that line. A confidence interval for the mean of Y at a chosen value x* uses only the first source: Ŷ ± t.05·SE. A prediction interval for a single new individual adds the second source, so it is always wider than the confidence interval. Both intervals widen as x* moves further from the mean of X1, because the line is pinned down most tightly near the centre of the data.

R² and adjusted R²

R² (the coefficient of determination) describes the amount of variance in the outcome “explained” by the predictor variables. One formula: R² = SSM/SST = 1 − (SSE/SST). Unfortunately, R² always increases as variables are added to the model. The adjusted R² = 1 − (MSE/MST) adjusts for the number of predictors and is useful for comparing models with different numbers of variables.

Testing groups of predictor variables

Sometimes it is necessary to simultaneously evaluate the significance of a group of X-variables (e.g., a set of indicator variables for a nominal variable). We compare the SSE of the full model with the SSE of the reduced model (without the group) using a partial F-test. This tells us whether the set of variables as a group contributes significantly to the model.

Interpreting the F-statistic

The F-test has a straightforward interpretation only when the X-variables are manipulated treatments in a controlled experiment. In observational studies, the F-statistic is influenced by the number of variables available, their correlations, the total number of subjects, and the method used for variable selection. Most variable selection methods tend to maximise F, meaning the observed F overestimates the actual significance of the model.

🎲 Interactive: What Does a p-Value Actually Mean?

Run hundreds of simulated studies. Each study fits a regression of Y on X with a chosen true effect and sample size. Watch the distribution of p-values build up. With no real effect, p-values are uniform on [0,1]. With a real effect, p-values pile up near zero. Power = the proportion below α.

One simulated study (most recent)

A scatter of n points; black line = OLS fit; t-statistic and p-value displayed.

Distribution of p-values across studies

Histogram of all p-values run so far. Red region = p < α (significant).

Last p-value
% significant (p < α)
Studies run
0
Theoretical power
Try this: switch truth to "no effect", run 1,000 studies. The histogram is flat; that is what a uniform p-value distribution looks like. Now switch to "real effect" and run again: the histogram piles up at zero. Power is just how much it piles up at zero.
Knowledge check: Section 2

1. What does the F-test in the ANOVA table assess?

The F-test from the ANOVA table tests the null hypothesis that all regression coefficients (except the intercept) are simultaneously equal to zero. It assesses the overall significance of the model.

2. What does R² (the coefficient of determination) measure?

R² = SSM/SST = 1 − (SSE/SST). It represents the amount of variance in the outcome variable that is “explained” or “accounted for” by the predictor variables in the model.

3. Why is adjusted R² preferred over R² when comparing models with different numbers of predictors?

R² always increases as variables are added to a regression model. The adjusted R² = 1 − (MSE/MST) accounts for the number of variables and will tend to decline if the added variables contain little additional information about the outcome.

Reflection

Consider a regression model you have seen in published research or coursework. How would you interpret the R² value? What does a low R² mean practically, and does it necessarily indicate a poor model?

Model answerR² quantifies the proportion of variance in the outcome explained by the predictors in the model. A low R² (e.g., 0.05) means 5% of variance is explained, which does not necessarily mean the model is bad. In epidemiology, low R² is common because health outcomes have many causes; even a well-specified model of CVD might have R² = 0.15 because genetics, environment, and chance all contribute. What matters is (a) whether the model coefficients are estimating the causal quantity of interest with reasonable precision, and (b) whether the model fits the data (residual diagnostics). A high R² with biased coefficients is worse than a low R² with unbiased ones (Anscombe, 1973). For prediction-focused work R² matters more; for causal inference, it's secondary to identification.
Reflection saved!
* Complete the quiz and reflection to continue.
Section 3 of 13

Nature of X-Variables & Collinearity

⏱ Estimated time: 20 minutes
Section 3 of 4

Nature of X-Variables & Collinearity

Scaling, indicator coding, hierarchical indicators, and diagnosing multicollinearity with the variance inflation factor.

Continuous predictors

Scaling and centering

Subtracting a reference value from X makes the intercept interpretable without changing the slope or its standard error.

Centered gestation (example)
\[ \color{#0B7B6B}{\text{gest39}} = \color{#C2410C}{\text{gest}} - 39 \]
gest39 centred gestation gest gestational age (weeks)

Before centering

Intercept = −1,514 g (birth weight at 0 weeks). Uninterpretable.

After centering at 39 weeks

Intercept = 3,341 g (birth weight at average gestation). Meaningful.

Categorical predictors

Indicator (dummy) variables

A nominal variable with \(j\) levels needs \(j - 1\) indicator variables. The omitted level is the reference category.

Race (3 levels) Race 1 Race 2 Race 3 (ref) 2 indicators X₁: 1 if Race 1, else 0 X₂: 1 if Race 2, else 0 Race 3: both = 0 β₁ = Race 1 vs Race 3 β₂ = Race 2 vs Race 3
Multicollinearity

Variance inflation factor

VIF formula (Eq 14.12)
\[ \color{#0B7B6B}{\text{VIF}_j} = \frac{1}{1 - \color{#C2410C}{R^2_{X_j}}} \]
VIFⱼ variance inflation, predictor j variance of Xj explained by other predictors

\(R^2_{X_j}\) is the R-squared from regressing \(X_j\) on all other predictors. VIF = 1: no collinearity. VIF > 10: serious inflation.

Before centering gest

Correlation between gest and gest-squared = 0.99. VIF = 131. SE of gest inflated 11-fold.

After centering

VIF drops to 1.54. SE returns near its original value. Interpretation restored.

Responding to collinearity

Three options, one principle

Drop one

Use the causal diagram to decide which correlated predictor is the more proximal cause.

Combine

Form a composite score or principal component from the correlated variables.

Keep with caution

If both are needed on substantive grounds, report the inflated standard errors and wide confidence intervals explicitly.

Collinearity inflates standard errors but does not bias coefficient estimates. Predictions remain accurate; individual coefficient interpretation does not.

Carry forward

What to take into the next section

  • Center continuous predictors to make the intercept meaningful and reduce collinearity in constructed terms.
  • A \(j\)-level nominal variable needs \(j - 1\) indicators with an explicit reference category.
  • Check VIF for all predictors. Values above 5 deserve attention; above 10 signals serious collinearity.

Introduction and Overview

An earlier section evaluated the model's overall fit. This section turns to a practical question that often determines whether your model gives sensible answers: are your predictors entered correctly? Continuous, categorical, indicator, and polynomial predictors all need different handling, and highly correlated predictors (multicollinearity) can destabilize coefficient estimates without obvious warning signs.

Learning Objectives

  • Choose appropriate scaling for continuous predictors so that coefficients are interpretable.
  • Convert nominal and ordinal categorical predictors into indicator variables (dummy coding).
  • Recognise hierarchical indicator structures and code them correctly.
  • Detect collinearity using correlation matrices and the variance inflation factor (VIF).
  • Decide when collinear predictors should be dropped, combined, or kept with caution.

Types of Predictor Variables

The X-variables can be continuous or categorical. Categorical variables can be either nominal (levels with no meaningful numerical representation, e.g., race or city of residence) or ordinal (ordered levels, e.g., severity: low, medium, high). Nominal and ordinal variables with more than 2 levels must be converted to indicator variables before entering the regression.

Scaling Variables

Often the predictor variables have a limited range of possible or sensible values. For example, if gestation length is a predictor, the intercept reflects birth weight at 0 weeks, which is meaningless. It is useful to scale these variables by subtracting the lowest possible sensible value (or the average) before entering them into the model. This makes the intercept interpretable without changing the regression coefficient or its SE.

Example: Subtracting 39 weeks (the average gestation length) from -gest- gives gest39 = gest − 39. Now β0 reflects birth weight for a 39-week gestation (3,341 gm), a much more meaningful value than the original constant of −1,514 gm.

Regular (Disjoint) Indicator Variables

Indicator variables (also called dummy variables) are created variables whose values have no direct physical relationship to the characteristic being described. For a nominal variable with j levels, we need j − 1 indicator variables. The omitted level becomes the referent (comparison) category.

Example: For mother’s race with 3 categories, we create 2 indicator variables (X1 and X2). Race 3 (with both indicators = 0) becomes the referent. β1 estimates the difference in outcome between races 1 and 3, while β2 estimates the difference between races 2 and 3.

Hierarchical (Incremental) Indicator Variables

If the predictor variables are ordinal in type (reflecting relative changes in an underlying characteristic), hierarchical indicator variables are often preferred. These contrast the outcome in each level against the level immediately preceding it (assuming all hierarchical variables are in the model).

Example: For mother’s education (4 levels), the disjoint indicators compare each level to the lowest (baseline). The hierarchical indicators instead show: the coefficient for level 4 reflects the difference between level 3 (some college) and level 4 (university degree), showing the incremental effect of each step up in education.

VariableIndicator CodingHierarchical Coding
meduc_c4=2 (high school diploma)20.04620.046
meduc_c4=3 (some college)53.27033.224
meduc_c4=4 (university degree)80.59927.329

Detecting Highly Correlated (Collinear) Variables

If the predictor variables are too highly correlated, a number of problems arise. The estimated effect of each variable depends on the other predictors in the model. With highly correlated predictors, the βs will be highly and negatively correlated, and in extreme cases none of the individual coefficients will be significantly different from zero despite a significant overall F-test.

VIFClick to explore
CentringClick to explore
Measurement ErrorClick to explore
Variance inflation factor (Eq 14.12)
\[ \color{#0B7B6B}{\text{VIF}_j} = \frac{1}{1 - \color{#C2410C}{R^2_{X_j}}} \]
The variance inflation factor for a predictor grows as the share of its variance explained by the other predictors approaches 1, signalling multicollinearity.

Collinearity Example

When a quadratic term (-gest_sq-) was added to a model already containing -gest-, the correlation between the two was 0.99, giving a VIF of 131. The SE of -gest- increased over 11 times (from 2.94 to 32.99). Centring -gest- by subtracting 39 (the mean) reduced the VIF from 131 to just 1.54 and the SE back down to 3.58.

Knowledge check: this section

1. For a nominal variable with 4 categories, how many indicator (dummy) variables are needed?

For a nominal variable with j levels, we need j − 1 indicator variables. The omitted level becomes the referent (reference) category for comparison. With 4 categories, we need 3 indicator variables.

2. What does a VIF value greater than 10 suggest?

A conservative guide for interpreting VIFs is that values above 10 indicate serious collinearity. While this does not necessarily mean the model is useless, it should always be taken as a warning about the interpretation of regression coefficients and the increase in their standard errors.

3. What is the primary purpose of centring a continuous variable before adding it to a regression model?

Centring reduces the correlation between a variable and its constructed derivatives (such as power terms or interaction terms). It does not change the predictions or the fit of the model, only the values and interpretation of the regression coefficients and the intercept.

Reflection

Why might highly correlated predictor variables cause problems in a multivariable regression model? What strategies would you use to detect and address collinearity in your own analyses?

Model answerHighly correlated predictors cause variance inflation: the OLS estimator distributes shared variance between the correlated predictors, producing large standard errors and unstable coefficients (a small change in data shifts a coefficient by a lot). The point estimates remain unbiased in expectation but are noisy (White, 1980; Long & Ervin, 2000). Detection: compute VIF (rule of thumb > 5 or > 10 is concerning), examine the correlation matrix among predictors, run condition indices on the design matrix. Strategies to address: (a) drop one of the correlated pair (justified by DAG: keep the one closer to the causal mechanism); (b) combine them into a single index (principal-component or composite score); (c) use shrinkage methods (ridge regression, LASSO) that handle collinearity by design (Belsley, Kuh, & Welsch, 1980); (d) increase sample size if feasible. None of these are a substitute for substantive thinking about whether both variables are needed.
Reflection saved!
* Complete the quiz and reflection to continue.
Section 4 of 13

Interaction & Causal Interpretation

⏱ Estimated time: 20 minutes
Section 4 of 4

Interaction & Causal Interpretation

Testing effect modification with a product term, and reading regression coefficients through a causal diagram.

Interaction terms

When one effect depends on another

Model with interaction (Eq 14.15)
\[ \color{#0B7B6B}{Y} = \beta_0 + \beta_1 \color{#1D4ED8}{X_1} + \beta_2 \color{#1D4ED8}{X_2} + \color{#C2410C}{\beta_3} (\color{#1D4ED8}{X_1} \times \color{#1D4ED8}{X_2}) + \varepsilon \]
Y outcome β₃ interaction coefficient X₁×X₂ product of predictors

If \(\beta_3 \neq 0\), the slope of \(X_1\) on \(Y\) equals \(\beta_1 + \beta_3 X_2\), changing with the value of \(X_2\).

Example 14.9: weight gain × birth order, \(\beta_3 = -88.4\), p = 0.010. High weight gain adds 227 g in first births but 139 g in later births.

Interactions in practice

Categorical interactions, and restraint

Categorical × categorical

Cross every indicator: a 3-level by 4-level interaction needs (3−1) × (4−1) = 6 product terms, tested together with a partial F-test.

Practical advice

Limit interactions to those with biological relevance. Investigate 3- and 4-way interactions only with good, biologically sound reasons.

Interpreting with interactions

Main effects at a specific value

Low X₂ High X₂ X₁ Y Interaction: different slopes across levels of X₂

When \(\beta_3 \neq 0\), plot the relationship of \(X_1\) and \(Y\) at representative values of \(X_2\) to communicate the interaction effect clearly.

Causal interpretation

The DAG decides what to adjust for

Smoking Gestation (mediator) Birth weight Exclude gestation for the total effect; include only for the direct effect
Confounders versus mediators

Two roles, two decisions

Confounder

Causes both exposure and outcome. Sits outside the causal path. Include it to reduce bias and estimate the total effect of the exposure.

Mediator (intervening variable)

Lies on the causal path from exposure to outcome. Exclude it to estimate the total effect. Include it only to estimate the direct effect.

The DAG, drawn before analysis, makes this classification explicit. Statistical tests cannot make this distinction for you.

Carry forward

What to take to the final assessment

  • A significant interaction term means the slope of one predictor changes across levels of another. Main effects must then be interpreted at specific values.
  • A DAG drawn before analysis decides which variables are confounders (adjust for them) and which are mediators (exclude for total effects).
  • The next lesson extends this to model-building strategies: deciding which variables should enter the model and in what order.

Introduction and Overview

Earlier sections set up a model with main effects only. This section takes two final design steps: testing whether the effect of one predictor depends on another (interaction) and giving the resulting coefficients a defensible causal interpretation. Both push linear regression beyond a curve-fitting exercise into a tool for answering causal questions, anchored in the DAG-based framework you met in an earlier lesson.

Learning Objectives

  • Specify and test interaction terms between two predictors.
  • Interpret a model with interactions correctly: main effects no longer have a single overall meaning.
  • Use a DAG to decide which covariates belong in the model for a causal question.
  • Distinguish confounders from mediators and explain why adjusting for a mediator can mislead.
  • Translate a fitted regression into a defensible causal claim, with explicit assumptions.

Detecting and Modelling Interaction

Given the component cause model, we might expect to see interaction when 2 factors act synergistically or antagonistically. In previous sections, models contained only main effects, assuming the association of X1 to Y is the same at all levels of X2. An interaction term tests whether the effect of one variable depends on the level of another.

Model with interaction term (Eq 14.15)
\[ \color{#0B7B6B}{Y} = \beta_0 + \beta_1 \color{#1D4ED8}{X_1} + \beta_2 \color{#1D4ED8}{X_2} + \color{#C2410C}{\beta_3} (\color{#1D4ED8}{X_1} \times \color{#1D4ED8}{X_2}) + \varepsilon \]
Adding the interaction coefficient on the product of two predictors lets the effect of one predictor depend on the level of the other.

We assess interaction by testing whether β3 = 0. If the interaction is absent (i.e., β3 is not significantly different from 0), the main effects (additive) model is deemed adequate. If the interaction is needed, centring becomes useful because it allows us to interpret β1 and β2 as linear effects when the centred version of the other variable is zero.

Interaction between two dichotomous variables

Example 14.9: The dichotomous versions of maternal weight gain (wtgain_c2: <30 lb vs ≥30 lb) and total birth order (tbo_c2: primiparous vs multiparous) were evaluated. The main effects model showed both factors were significant. Adding the interaction term (wg_c2*tbo_c2) revealed a significant interaction (β3 = −88.4, P = 0.010).

This means the positive effect of multiparous birth on birth weight is present if weight gain is low, but is negligible if weight gain is high. Similarly, high weight gain has a bigger effect in primiparous births (227 gm) than in multiparous births (139 gm).

Interactions with categorical variables

Interactions involving categorical variables (with more than 2 levels) are modelled by including products between all indicator variables needed in the main effects model. For example, the interaction between a 3-level and a 4-level categorical variable requires (3−1) × (4−1) = 6 product variables. These 6 variables should be tested and explored as a group using the partial F-test.

Practical advice on interaction terms

In many multivariable analyses, the number of possibilities for interaction is large and there is no single correct way to assess if interaction is present. Unless the potential number of interactions is small, interactions should be limited to those of biological relevance. It is generally recommended that 3- and 4-way interactions only be investigated when there are good, biologically sound reasons for doing so.

Causal Interpretation of a Multivariable Linear Model

So far, we have focused on the technical interpretation of regression coefficients. When making causal inferences, extra care is needed to ensure that only the appropriate variables are included in the analysis. A causal diagram is very helpful in this regard.

Key Causal Principle

If a variable is an intervening variable (on the causal pathway between exposure and outcome), including it in the model will change the interpretation (Greenland, Pearl, & Robins, 1999). For example, if gestation length is an intervening variable between cigarette smoking and birth weight, including -gest- in the model adjusts away part of the causal effect of smoking. The total effect of smoking would be obtained from a model without -gest-, while the direct effect (not mediated through gestation) would require including it.

Example: Causal Model for Smoking & Birth Weight

Our objective is to evaluate the effects of cigarette smoking (-cig-) on birth weight (-bwt-). The causal diagram indicates that gestation length (-gest-) is an intervening variable between -cig- and -bwt-. Consequently, -gest- and -wtgain- should be excluded from the model when estimating the total causal effect of smoking on birth weight.

The model includes: -white- (potential confounder), -college- (potential confounder), and -cig_2- (the exposure of interest). The interaction between -cig_2- and -white- was assessed.

Total EffectClick to explore
Direct EffectClick to explore
Confounders vs InterveningClick to explore
Knowledge check: this section

1. What does a significant interaction term (β3) in a regression model indicate?

A significant interaction term indicates that the association between one predictor and the outcome varies across levels of the other predictor. The main effects (additive) model is no longer sufficient to describe the relationship.

2. When estimating the total causal effect of an exposure, what should you do with intervening variables?

Including intervening variables in the model adjusts away part of the causal effect that operates through the mediator. To estimate the total effect, intervening variables should be excluded; including them gives the direct effect only.

3. What tool is recommended before building a multivariable model to help distinguish confounders from intervening variables?

A causal diagram (directed acyclic graph) is very helpful for identifying which variables are confounders (should be included), which are intervening variables (may need to be excluded for total effects), and which are effects of the outcome (should not be included).

Reflection

Consider an exposure–outcome relationship you are interested in. Draw (or describe) a causal diagram identifying potential confounders and intervening variables. How would the choice of which variables to include affect your estimate of the causal effect?

Model answerFor an exposure (say, dietary fibre intake) and outcome (incident type-2 diabetes), DAG: fibre → diabetes, with confounders age, sex, SES, BMI at baseline, physical activity, smoking, family history (all pointing into both fibre intake and diabetes). Intervening variables: HbA1c, insulin sensitivity, weight change during follow-up, on the causal pathway. Effect of variable inclusion: (a) adjusting for confounders gives an unbiased causal effect of fibre on diabetes (the total effect); (b) adjusting for an intervening variable (e.g., HbA1c) gives the direct effect bypassing that mediator, but blocks the indirect effect, attenuating the total causal effect estimate; (c) adjusting for a collider (e.g., a hospitalisation event affected by both fibre and diabetes status) introduces selection bias. The DAG forces these distinctions explicit; routine "control for everything" defaults blur them and produce biased estimates.
Reflection saved!
* Complete the quiz and reflection to continue.
Section 5 of 13

Introduction & The Logistic Model

⏱ Estimated time: 20 minutes
Lesson 5

Logistic Regression

The workhorse model for outcomes with only two possible answers: disease or no disease, alive or dead, exposed or not.

Where this fits

From continuous outcomes to yes-or-no outcomes

Linear regression

Predicts a continuous outcome that can take any value, such as blood pressure, weight, or cholesterol.

Logistic regression

Predicts a binary outcome with two states, coded 1 (event happened) or 0 (it did not), such as disease yes or no.

Formalised by David Cox in 1958; the standard model for dichotomous outcomes in epidemiology.

Three problems

Why a straight line fails for a yes-or-no outcome

Errors aren't bell-shaped

With a 0/1 outcome the leftover errors follow a binomial pattern, not the normal curve linear regression assumes.

Uneven spread

The variability of the errors changes with the predicted probability, breaking the constant-spread assumption.

Impossible predictions

A straight line can predict a probability above 1 or below 0, which is nonsense for a probability.

The key idea

Model the log odds, not the probability

Odds, then the log of the odds (the logit)
\[ \color{#C2410C}{\text{odds}} = \frac{\color{#0B7B6B}{p}}{1-\color{#0B7B6B}{p}} \qquad \color{#6D28D9}{\text{logit}(p)} = \ln\!\left(\frac{\color{#0B7B6B}{p}}{1-\color{#0B7B6B}{p}}\right) \]
p probability of the event odds p / (1 − p) logit natural log of the odds

A probability sits between 0 and 1. Its odds run from 0 upward. The log of the odds runs from very negative to very positive, the full number line, which is exactly what a linear model needs.

The logistic model

Linear on the log-odds scale

Log-odds scale (Eq 16.2)
\[ \ln\!\left(\frac{\color{#0B7B6B}{p}}{1-\color{#0B7B6B}{p}}\right) = \color{#C2410C}{\beta_0} + \color{#6D28D9}{\beta_1} \color{#1D4ED8}{x_1} + \color{#6D28D9}{\beta_2} \color{#1D4ED8}{x_2} + \dots \]
p probability β₀ intercept βⱼ coefficient j xⱼ predictor j
Back to the probability scale (Eq 16.3)
\[ \color{#0B7B6B}{p} = \frac{1}{1 + e^{-(\color{#C2410C}{\beta_0} + \sum \color{#6D28D9}{\beta_j} \color{#1D4ED8}{x_j})}} \]
p probability (0 to 1) β₀ intercept βⱼ coefficient j xⱼ predictor j

No error term: the randomness enters through the binary outcome itself.

Reading the model

A coefficient becomes an odds ratio

Odds ratio for a predictor (Eq 16.6)
\[ \color{#0B7B6B}{\text{OR}_k} = e^{\color{#C2410C}{\beta_k}} \]
ORₖ odds ratio for predictor k βₖ its log-odds coefficient

Raise e to the coefficient and you get the adjusted odds ratio. For a smoker/non-smoker predictor, an OR of 2 means smokers have twice the odds of the outcome, holding everything else fixed.

Odds ratios are not risk ratios; when the outcome is common they can overstate the apparent strength of an association.Norton, Dowd & Maciejewski (2018)
Fitting the model

Maximum likelihood, and a worked example

Maximum likelihood estimation: rather than least squares, the computer searches for the coefficients that make the observed data most probable, guessing, checking, and refining until the changes are tiny (convergence).

Low birth weight study

Outcome: born under 2500 g, yes/no. Predictors: smoking, race, prenatal visits. Then e to the smoking coefficient is the adjusted odds ratio for smoking.

Introduction and Overview

Earlier lessons worked through linear regression for continuous outcomes. This lesson takes the most common alternative in epidemiology: the binary outcome (disease present/absent, vaccinated/unvaccinated, alive/dead). The logistic model was formalised by Cox (1958) and has since become the workhorse logistic regression for dichotomous outcomes in epidemiology. The four content sections walk through this in order: why ordinary linear regression breaks down for binary outcomes and what the logistic model replaces it with (this section), the assumptions and how to test the overall model and individual coefficients (a later section), goodness-of-fit and predictive ability (a later section), and finally extensions including generalised linear models and exact logistic regression for sparse data (a later section). The odds ratios you computed by hand in an earlier course reappear here as exponentiated regression coefficients.

Learning Objectives

  • Explain why linear regression fails for dichotomous outcomes and how the logit transformation solves the problem.
  • Write down the logistic model on both the log-odds and probability scales.
  • Translate a regression coefficient into an odds ratio using OR = eβ.
  • Describe how maximum likelihood estimation finds the coefficients that best fit binary data.

Why We Cannot Use Linear Regression for Dichotomous Outcomes

When the outcome variable is dichotomous (e.g., disease present/absent), ordinary linear regression is inappropriate for three fundamental reasons:

  1. Non-normal errors: The residuals from a linear model with a binary outcome follow a binomial distribution, not a normal distribution, violating a key assumption of linear regression.
  2. Heteroscedasticity: The variance of the residuals depends on the predicted probability, so the assumption of constant variance is violated.
  3. Predictions outside 0–1: A linear model can produce predicted values less than 0 or greater than 1, which are nonsensical for probabilities.

Key Concept

Logistic regression solves all three problems by modelling the log odds (logit) of the outcome rather than the probability directly (Cox, 1958). The logit transformation maps probabilities from the bounded range (0, 1) to the entire real number line (−∞, +∞), making it suitable for linear modelling.

Why Not Linear Regression?Click to explore
Logit TransformClick to explore
Odds Ratio (OR = eβ)Click to explore

The Logistic Model

The logistic regression model expresses the log odds of the outcome as a linear combination of predictors:

The logit model (Eq 16.2)
\[ \ln\!\left(\frac{\color{#0B7B6B}{p}}{1 - \color{#0B7B6B}{p}}\right) = \color{#C2410C}{\beta_0} + \color{#6D28D9}{\beta_1} \color{#1D4ED8}{x_1} + \color{#6D28D9}{\beta_2} \color{#1D4ED8}{x_2} + \dots \]
The log-odds of the outcome (the natural log of probability over one minus it) is a linear combination of the intercept and each coefficient times its predictor.

The inverse logit (or logistic function) converts back to the probability scale:

Probability from the logistic model (Eq 16.3)
\[ \color{#0B7B6B}{p} = \frac{1}{1 + e^{-(\color{#C2410C}{\beta_0} + \sum \color{#6D28D9}{\beta_j} \color{#1D4ED8}{x_j})}} \]
Inverting the logit gives the probability as the logistic function of the intercept plus each coefficient times its predictor. The result is always between 0 and 1.

Note that, unlike linear regression, the logistic model has no error term because it models on the logit scale. The randomness enters through the binomial distribution of the outcome.

Odds and Odds Ratios

The odds of the outcome are p / (1 − p). The odds ratio for the kth predictor is obtained by exponentiating its coefficient:

Odds ratio (Eq 16.6)
\[ \color{#0B7B6B}{\text{OR}_k} = e^{\color{#C2410C}{\beta_k}} \]
The odds ratio for a predictor is the exponential of its log-odds coefficient, the multiplicative change in odds per one-unit increase.

For a dichotomous predictor, this is the odds ratio comparing the group coded 1 to the group coded 0, adjusted for all other variables in the model. Care is needed in interpretation: odds ratios are not risk ratios and can exaggerate the apparent strength of association when the outcome is common (Norton, Dowd, & Maciejewski, 2018).

Worked example: from a coefficient to an odds ratio, and from the model to a probability

Take a fitted model for a yes/no outcome with intercept β0 = -1.6 and a single smoking coefficient β1 = 0.69 (smoker = 1, non-smoker = 0). Reading it takes three short steps, and it is worth doing the arithmetic once by hand.

1. Log odds. Add up the linear part. For a non-smoker that is just the intercept, -1.6. For a smoker it is -1.6 + 0.69 = -0.91.

2. Odds, then probability. Exponentiate the log odds to get the odds, then turn odds into a probability with p = odds / (1 + odds). Non-smoker: odds = e-1.6 = 0.20, so p = 0.20 / 1.20 = 0.17. Smoker: odds = e-0.91 = 0.40, so p = 0.40 / 1.40 = 0.29.

3. Odds ratio. The odds ratio for smoking is the ratio of the two odds, 0.40 / 0.20 = 2.0, which is exactly e0.69. This is the same OR = eβ from the formula above, now seen from the raw odds rather than the coefficient.

The example also makes one caution concrete. The risk ratio here is 0.29 / 0.17 = 1.7, noticeably smaller than the odds ratio of 2.0. When the outcome is common, the odds ratio sits further from 1 than the risk ratio, which is why an odds ratio can overstate how much the underlying risk really changes.

➹ Interactive: Logistic S-Curve Explorer

Slide the intercept (β₀) and slope (β₁). The linear-in-log-odds world (left) and the nonlinear-in-probability world (right) are two views of the same model. The S-curve’s steepness is set by β₁; its midpoint is set by −β₀/β₁.

Log-odds (linear) view: η = β₀ + β₁X
Probability (S-curve) view: p = 1/(1 + e^−η)
OR per +1 unit X
p at X = 0
p at X = ref
X50% (midpoint)
Try this: hold β₁ at 1.0 and slide β₀. The whole S-curve shifts left/right but doesn't change shape. Now hold β₀ and slide β₁: the steepness of the S changes. β₁=0 produces a flat line at p = 1/(1+e^−β₀).

Maximum Likelihood Estimation (MLE)

Unlike linear regression, which uses least squares, logistic regression uses maximum likelihood estimation (MLE). MLE is an iterative process that finds the parameter values most likely to have produced the observed data. The algorithm starts with initial estimates and refines them until convergence, the point at which the change in the log-likelihood between iterations falls below a specified criterion.

📋 Example: Low Birth Weight Study

Consider a study of low birth weight (<2500 g) as the outcome. Predictors include the mother’s smoking status, race, and number of prenatal visits. Because the outcome is dichotomous (low birth weight: yes/no), logistic regression is appropriate.

The model would be: ln(p / (1 − p)) = β0 + β1(smoking) + β2(race) + β3(prenatal visits). From the fitted model, eβ1 gives the adjusted odds ratio for smoking, comparing smokers to non-smokers while holding race and prenatal visits constant.

Knowledge check: this section

1. What does the logit function transform?

The logit function takes a probability p (bounded between 0 and 1) and transforms it to ln(p/(1−p)), the log of the odds, which ranges from −∞ to +∞. This allows probabilities to be modelled as a linear function of predictors.

2. In a logistic regression, how is the odds ratio for a dichotomous predictor computed?

The odds ratio is obtained by exponentiating the logistic regression coefficient: OR = eβ. For a dichotomous predictor, this gives the ratio of the odds of the outcome in the exposed group versus the unexposed group, adjusted for other covariates.

3. Why is maximum likelihood estimation (MLE) used instead of least squares for logistic regression?

Least squares estimation assumes normally distributed errors, which is violated when the outcome is binary (errors follow a binomial distribution). MLE finds parameter values that maximise the probability of observing the data, making it appropriate for binary outcomes.

✎ Reflection

Think about a dichotomous health outcome in your field. What predictors would you include in a logistic regression model? Why is modelling on the logit scale preferable to modelling the probability directly?

Model answerPick a dichotomous outcome (e.g., incident type-2 diabetes within 5 years). Predictors: demographic (age, sex, ethnicity, SES), lifestyle (physical activity, smoking, alcohol, diet pattern), clinical (BMI, blood pressure, fasting glucose, family history). Why logit scale: (a) probabilities are bounded [0,1], so linear predictors of probability can exceed bounds and produce nonsense fitted values; (b) the logit transformation maps probabilities to (−∞, ∞), allowing a linear additive model on the logit scale; (c) the resulting coefficients have a clean odds-ratio interpretation that is invariant to the marginal distribution of the outcome; (d) the model has well-behaved likelihood and standard inference. Modelling probability directly (linear probability model) can be useful for descriptive purposes but distorts inference, especially at extreme probabilities.
✓ Reflection saved!
Complete the quiz and reflection to continue.
Section 6 of 13

Interpreting Coefficients & Assessing Confounding

⏱ Estimated time: 20 minutes
Section 2 of 4

Interpreting Coefficients & Assessing Confounding

Checking the assumptions, testing the model, reading each coefficient as an odds ratio, and spotting confounding and interaction.

The two assumptions

What logistic regression assumes

Independence

Each observation's outcome stands on its own. Clustered data (patients within a hospital) violate this.

Linearity on the logit scale

Each one-unit rise in a continuous predictor shifts the log odds by a constant amount. On the probability scale the curve is S-shaped, not straight.

Testing the model

Likelihood ratio test and Wald test

Likelihood ratio statistic, full vs null (Eq 16.9)
\[ \color{#0B7B6B}{G^2_0} = 2(\ln \color{#C2410C}{L} - \ln \color{#6D28D9}{L_0}) \]
G²₀ likelihood ratio statistic L likelihood, full model L₀ likelihood, null model

Compares a fitted model to the intercept-only model (or any two nested models). Follows a chi-squared distribution; degrees of freedom equal the number of added predictors.

The Wald test divides one coefficient by its standard error and checks it against a normal distribution, which the test software reports by default.

A caution

When the Wald test misleads

Near a probability of 0 or 1, or with a small sample, the coefficient and its standard error are poorly approximated, so the Wald test can mislead. The likelihood ratio test has better properties and is preferred there.Vittinghoff & McCulloch (2007)
Interpretation, part 1

Dichotomous and continuous predictors

Two-state predictor

Coefficient = log odds ratio for group 1 vs group 0. If β = 0.69, OR = e0.69 = 2.0: twice the odds.

Continuous predictor

OR per unit = eβ. For any change, OR = eβ(x₂−x₁). Age β = 0.04 → per 10 years, e0.4 = 1.49.

OR for a change of (x₂ − x₁) units (Eq 16.13)
\[ \color{#0B7B6B}{\text{OR}} = e^{\color{#C2410C}{\beta}(\color{#1D4ED8}{x_2} - \color{#1D4ED8}{x_1})} \]
OR odds ratio for the change β coefficient x₂−x₁ size of the change
Interpretation, part 2

Categorical predictors and the intercept

Categorical (3+ levels)

Split into indicator variables against one reference level. Test the whole set with a multi-df Wald test or a likelihood ratio test.

Intercept (β₀)

Log odds when all predictors are zero. Often not meaningful on its own, but needed for predicted probabilities.

Effects on the probability scale are non-linear: the same predictor change moves probability differently depending on the baseline.

Confounding and interaction

When another variable changes the picture

Confounding

Add the suspected confounder; if the coefficient of interest shifts by more than about 10–20%, keep it in, regardless of its own p-value.

Interaction (effect modification)

Add a cross-product term. A significant term means the odds ratio for one variable depends on the level of another.

Multiplicative interaction on the logit scale does not imply additive interaction on the risk scale, an important distinction for public-health interpretation.Knol et al. (2008)

Introduction and Overview

An earlier section set up the model and showed how its coefficients become odds ratios on the exponentiated scale. This section turns to the same questions you asked of linear regression in an earlier lesson: are the assumptions met, is the overall model significant, what do the individual coefficients mean, and how do confounding and interaction enter the picture? Most of the framework is identical; the differences are mostly in how we compute and interpret coefficients on the log-odds scale.

Learning Objectives

  • State the two key assumptions of logistic regression and how to check them.
  • Compare the likelihood ratio test and Wald test for the overall model and individual coefficients.
  • Interpret coefficients for dichotomous, categorical, and continuous predictors as adjusted odds ratios.
  • Use changes in coefficients and stratified analysis to evaluate confounding and interaction.

Assumptions of Logistic Regression

Logistic regression requires two key assumptions: (1) independence of observations, and (2) linearity on the logit scale, that is, the relationship between each continuous predictor and the log odds of the outcome is linear. Note that the relationship on the probability scale will be non-linear (S-shaped).

Testing the Overall Model

The likelihood ratio test (LRT) compares the fitted model to the null model (intercept only). The test statistic is:

Likelihood ratio test: full vs null model (Eq 16.9)
\[ \color{#0B7B6B}{G^2_0} = 2(\ln \color{#C2410C}{L} - \ln \color{#6D28D9}{L_0}) \]
The likelihood ratio statistic is twice the difference between the log-likelihood of the full model and that of the null model. Larger values favour the full model.

This statistic follows an approximate chi-squared distribution with degrees of freedom equal to the number of predictors. It can also be used to compare any two nested models (Eq 16.10), a full model versus a reduced model, to test whether the excluded variables contribute significantly.

The Wald test divides the coefficient by its standard error (following a Z distribution) and is more commonly reported by software. However, Wald tests can be unreliable when the true probability is near 0 or 1, or when the sample size is small (Vittinghoff & McCulloch, 2007).

⚠ Wald Test Limitations

The Wald test can be unreliable when the estimated probability is near the boundary (0 or 1), because the coefficient estimate and its standard error may be poor approximations. In such cases, the likelihood ratio test is preferred as it has better statistical properties.

Interpreting Coefficients

Dichotomous Predictors

For a dichotomous predictor (coded 0/1), the coefficient β represents the log odds ratio comparing the group coded 1 to the group coded 0, adjusted for all other variables. The odds ratio is simply OR = eβ. For example, if βsmoking = 0.69, then OR = e0.69 = 2.0, meaning the odds of the outcome are twice as high for smokers compared to non-smokers.

Continuous Predictors

For a continuous predictor, β represents the change in the log odds for each 1-unit increase in the predictor. The OR = eβ gives the multiplicative change in odds per unit increase. To compute the OR for any arbitrary change from x1 to x2:

OR for a change of (x₂ − x₁) units (Eq 16.13)
\[ \color{#0B7B6B}{\text{OR}} = e^{\color{#C2410C}{\beta}(\color{#1D4ED8}{x_2} - \color{#1D4ED8}{x_1})} \]
For a change from one predictor value to another, the odds ratio is the exponential of the coefficient times the size of that change.

For example, if βage = 0.04, the OR per 10-year increase in age is e0.04 × 10 = e0.4 = 1.49.

Categorical Predictors (Multiple Levels)

Categorical predictors with more than two levels are represented using indicator (dummy) variables. One category serves as the baseline/reference, and each coefficient represents the log OR comparing that category to the reference. To evaluate the overall significance of the categorical variable, use a multi-degree-of-freedom Wald test or an LRT comparing models with and without the entire set of indicator variables.

Intercept Interpretation

The intercept (β0) represents the logit of the probability of the outcome when all predictors equal zero. On the probability scale, this is: p = 1/(1 + e−β0). The intercept is often not substantively meaningful (e.g., if age = 0 is not a plausible value), but it is essential for computing predicted probabilities. Note that effects on the probability scale are non-linear: the same change in a predictor produces different changes in probability depending on the baseline values of all predictors.

R Activity: fit a logistic regression and convert coefficients to odds ratios

The course dataset includes a binary hypertension outcome (Yes/No) we will use here. The full annotated script is in r-activities/HSCI_410_Lesson_5_Logistic_Regression.R; the highlights:

# 0. Load + ensure outcome has the REFERENCE level FIRST ("No")
phaa <- read.csv("phaa_survey_clean.csv", stringsAsFactors = FALSE)
phaa$hypertension <- factor(phaa$hypertension, levels = c("No", "Yes"))
phaa$smoker       <- factor(phaa$smoker,       levels = c("No", "Yes"))

# 1. Crude (unadjusted) model -----------------------------------------------
glm_1 <- glm(hypertension ~ smoker,
             data   = phaa,
             family = binomial(link = "logit"))
summary(glm_1)
exp(coef(glm_1))      # crude odds ratio
exp(confint(glm_1))   # 95% CI for the OR

# 2. Adjusted (multivariable) model -----------------------------------------
glm_2 <- glm(hypertension ~ smoker + age + gender + bmi + dep_score,
             data   = phaa,
             family = binomial)
summary(glm_2)
or  <- exp(coef(glm_2))
ci  <- exp(confint(glm_2))
round(cbind(OR = or, ci, p = summary(glm_2)$coef[,"Pr(>|z|)"]), 3)

# 3. Likelihood-ratio test for nested models ---------------------------------
anova(glm_1, glm_2, test = "Chisq")

# 4. Goodness-of-fit and discrimination --------------------------------------
library(generalhoslem);  library(DescTools);  library(pROC)
logitgof(obs = glm_2$y, fitted(glm_2))   # Hosmer-Lemeshow
PseudoR2(glm_2, which = "all")             # McFadden / Nagelkerke
phaa$pred_htn <- predict(glm_2, type = "response")
auc(roc(phaa$hypertension, phaa$pred_htn,
        levels = c("No", "Yes")))

Read the table. An OR of 2.0 for smokerYes means smokers have twice the odds of hypertension as non-smokers, holding age, gender, BMI, and depression score constant. Confounding check (a later lesson of an earlier course): if the crude OR from glm_1 differs meaningfully from the adjusted OR in glm_2, one or more of the added covariates is confounding the smoking-hypertension relationship.

R Reflect on what you just ran

Use the questions below to interpret the output you produced. Look at your console / plot before answering.

1. From exp(coef(glm_1)) and exp(coef(glm_2)), what are the crude and adjusted odds ratios for smokerYes? By what percent did the OR change after adjustment? Does that change exceed a 10% rule-of-thumb threshold for confounding?

Model answerexp(coef(glm_1)) typically gives a crude OR for smokerYes around 1.85, and exp(coef(glm_2)) after adjustment around 1.55, a roughly 16% reduction. That exceeds the 10% rule-of-thumb threshold and signals that one or more measured covariates (age, BMI, sex) was confounding the crude smoking-hypertension association. The interpretation: adjusted smokers have ~55% higher odds of hypertension than non-smokers, accounting for measured confounders, meaningfully smaller than the unadjusted gap but still substantial.

2. From the tidied table (round(cbind(OR, ci, p), 3)), which predictors have a 95% CI that excludes 1.0? Pick one and translate its OR into a one-sentence interpretation on the odds scale.

Model answerPredictors with 95% CI excluding 1.0 typically include age, BMI, and smokerYes; sex may be borderline. Example interpretation: an OR of 1.55 for smokerYes (95% CI 1.21, 1.99) means smokers have 1.55-fold higher odds of hypertension compared with non-smokers, holding other covariates constant. The CI excludes 1, so the effect is statistically significant at α = 0.05.

3. Report the Hosmer-Lemeshow p-value, the McFadden pseudo R-squared, and the AUC from the ROC curve. Does the model fit well, and how good is its discrimination between people with and without hypertension?

Model answerHosmer-Lemeshow p-value typically around 0.30–0.50 (high p means no evidence of poor fit, which is good); McFadden pseudo-R² around 0.10–0.15 (modest, but interpreted differently from linear R²; values 0.2–0.4 indicate good fit on this scale); AUC around 0.75 (acceptable discrimination, conventionally 0.7–0.8 = acceptable, 0.8–0.9 = good). The model fits adequately and discriminates moderately well between people with and without hypertension.
Saved.

Assessing Confounding and Interaction

Assessing Confounding

To assess whether a variable is a confounder, add it to the model and check whether the coefficient of the primary predictor of interest changes substantially. A common rule of thumb is a change of more than 10–20% in the coefficient (or OR). If the coefficient changes meaningfully, the variable should be retained as a confounder regardless of its statistical significance.

Assessing Interaction (Effect Modification)

Interaction is assessed by adding cross-product terms (e.g., x1 × x2) to the model. When an interaction is present, the odds ratio for one variable varies depending on the level of the interacting variable. For example, if smoking interacts with sex, the OR for smoking would differ between males and females. Test the interaction term using an LRT or Wald test. If significant, the main effects alone are insufficient to describe the relationship. Note that multiplicative interaction on the logit scale does not necessarily imply additive interaction on the risk scale, an important consideration for public-health interpretation (Knol et al., 2008).

Knowledge check: this section

1. The likelihood ratio test (LRT) compares models by:

The LRT statistic is G² = 2(ln Lfull − ln Lreduced), which follows a chi-squared distribution. It tests whether the additional parameters in the full model significantly improve the fit compared to the reduced model.

2. For a continuous predictor, what does the odds ratio represent?

For a continuous predictor, OR = eβ represents the factor by which the odds are multiplied for each 1-unit increase in the predictor, holding all other variables constant. To compute the OR for a larger change, use OR(x2 − x1).

3. When assessing confounding in logistic regression, you should:

Confounding is assessed by adding the potential confounder to the model and checking whether the coefficient of the primary predictor changes substantially (often a threshold of 10–20%). If it does, the variable should be retained as a confounder regardless of its own P-value.

✎ Reflection

Imagine you are fitting a logistic regression model for a health outcome. How would you decide whether to report odds ratios per 1-unit increase or per a larger clinically meaningful increment for continuous predictors? Why does this matter for interpretation?

Model answerFor a continuous predictor like age, reporting OR per 1-unit increase makes the OR very close to 1 (e.g., OR = 1.04 per year of age) and hard to interpret clinically. Better practice: report OR per 10-year increase (OR = 1.48 = 1.04¹°) or per IQR or per SD. The choice depends on the clinical/policy unit of intervention: BMI per 5-unit increment, BP per 10-mmHg increment, cholesterol per 1-mmol/L increment. This matters because (a) it makes the magnitude of association visible to a clinical reader, (b) it scales the OR to a clinically actionable change, and (c) it avoids the impression of a tiny effect that is actually large in standard units. Always state explicitly the unit increment in the table and report both raw coefficient and scaled OR.
✓ Reflection saved!
Complete the quiz and reflection to continue.
Section 7 of 13

Evaluating Logistic Regression Models

⏱ Estimated time: 25 minutes
Section 3 of 4

Evaluating Logistic Regression Models

Residuals, goodness-of-fit, discrimination and calibration, overdispersion, pseudo R-squared, and influential observations.

Before you evaluate

Building the model, and how many events you need

Same discipline as linear regression: start from a causal diagram, run univariable analyses, check linearity on the logit scale, and use automated selection with caution.

10(k + 1)minimum events (outcomes), where k is the number of predictors. Five predictors → at least 60 events.
Residuals

Where does the model fit badly?

A residual is the gap between the observed outcome and the predicted probability. Two flavours, scaled differently:

Pearson residuals

Standardise the observed-minus-expected gap by its expected variability.

Deviance residuals

Based on each pattern's contribution to the overall lack of fit.

Large residuals flag covariate patterns the model fits poorly. They are also the building blocks of goodness-of-fit tests (Eq 16.16).

Goodness of fit

The Hosmer-Lemeshow test

Sort everyone by predicted probability, split into ten groups (deciles of risk), and in each group compare observed outcomes to expected. Good calibration means they match across all groups.

A non-significant (high) p-value is the good result: no evidence of misfit. With large samples, though, it can reject trivial misfit, so interpret it alongside other measures.Hosmer & Lemeshow (1980)
Discrimination

Sensitivity, specificity, and the ROC curve

TermMeaning
SensitivityTrue cases correctly flagged (true positive rate)
SpecificityTrue non-cases correctly cleared (true negative rate)
CutpointProbability threshold for calling someone positive

Lower the cutpoint: more sensitivity, less specificity. The ROC curve shows this trade-off across all cutpoints.

AUC and calibration

Two different questions

Discrimination (area under the curve)

Chance the model gives a true case a higher predicted risk than a true non-case. 0.5 = coin flip; 0.7–0.8 acceptable; 0.8–0.9 good; 1.0 perfect.

Calibration

When the model says 20% risk, do about 20% actually have the outcome? Checked with a calibration plot of predicted vs observed.

Hanley & McNeil (1982) on the ROC curve; Steyerberg and colleagues (2010) on calibration.

Overdispersion

More variability than the model expects

Apparent

A false alarm from many sparse covariate patterns. Not real extra variation; lean on the Hosmer-Lemeshow test instead.

Real

Genuine extra variation, often from clustering. Fix by adjusting standard errors or using models for clustered data.

Detect it by the ratio of Pearson chi-squared (or deviance) to its degrees of freedom: near 1 is fine, well above 1 signals overdispersion.

Pseudo R-squared and influence

Explained variation and outsized points

Pseudo R-squared

McFadden, Cox-Snell, Nagelkerke approximate explained variation. Not interchangeable; run lower than linear R-squared.

Influential observations

Outliers, high leverage, and delta-beta / delta-chi-squared / delta-deviance flag points that move a coefficient or the fit too much.

Birth weight example: an area under the curve of 0.623 is weak discrimination: useful for risk factors, but the predictors explain little of the outcome.

Introduction and Overview

An earlier section covered model construction and interpretation. This section turns to model evaluation: residuals, formal goodness-of-fit tests (Hosmer & Lemeshow, 1980), predictive ability via discrimination (ROC curves; Hanley & McNeil, 1982) and calibration, the question of overdispersion, pseudo-R² statistics, and influential observations. Each gives a different angle on whether the model you've built is actually fit for the question you're asking (Steyerberg et al., 2010).

Learning Objectives

  • Distinguish Pearson and deviance residuals and use them to flag poorly fit covariate patterns.
  • Apply the Hosmer–Lemeshow test and interpret its result alongside other goodness-of-fit measures.
  • Quantify predictive ability using ROC curves, AUC, and calibration plots.
  • Recognise overdispersion in binomial data and explain how pseudo-R² statistics summarise model fit.
  • Identify influential observations using leverage and Cook's distance equivalents for logistic models.

Model-Building Process

The model-building process for logistic regression follows the same general principles as for linear regression (Chapter 15): develop a causal diagram, perform unconditional (univariable) analyses, evaluate linearity of continuous predictors on the logit scale, and use automated selection methods with caution. Subject matter knowledge should guide decisions at every step.

Covariate Patterns and Data Structure

A covariate pattern is a unique combination of predictor values. Whether the data are treated as binary (one observation per row) or binomial/grouped (multiple observations per covariate pattern) has implications for how residuals and goodness-of-fit statistics are computed and interpreted.

Sample Size Rule

A commonly used minimum sample size guideline for logistic regression is at least 10(k + 1) positive outcomes, where k is the number of predictors. For example, if you have 5 predictors, you need at least 10(5 + 1) = 60 positive outcomes (events). Having fewer events can lead to unreliable coefficient estimates and model instability, though simulation work has shown this rule can be relaxed in some scenarios (Vittinghoff & McCulloch, 2007).

Residuals

Pearson residuals and deviance residuals are used to assess model fit at the level of individual covariate patterns (Eq 16.16). Both types compare observed outcomes to predicted probabilities, but they differ in how discrepancies are scaled. These residuals are the building blocks of several goodness-of-fit tests.

Goodness-of-Fit Tests

Pearson χ²Click to explore
Hosmer-LemeshowClick to explore
ROC CurveClick to explore

Predictive Ability

Discrimination is most often summarised by the area under the receiver operating characteristic (ROC) curve (Hanley & McNeil, 1982), while calibration assesses agreement between predicted and observed risks (Steyerberg et al., 2010).

A receiver operating characteristic curve rising above the diagonal chance line, with area under the curve of about 0.62.
The ROC curve traces sensitivity against one minus specificity across all classification thresholds. The area under it (here about 0.62, as in the birth-weight example) is the probability that a random case is ranked above a random non-case; 0.5 is chance.
ConceptDefinitionAlso Known As
SensitivityProportion of true positives correctly identified by the modelTrue positive rate
SpecificityProportion of true negatives correctly identified by the modelTrue negative rate
CutpointThe predicted probability threshold above which subjects are classified as positiveClassification threshold

Selecting a cutpoint involves a trade-off between sensitivity and specificity. A lower cutpoint increases sensitivity but decreases specificity, and vice versa. The ROC curve provides a visual summary of this trade-off across all possible cutpoints.

Overdispersion

Apparent Overdispersion

Apparent overdispersion occurs when the Pearson χ² statistic is inflated, not because of true extra-binomial variation, but because there are many covariate patterns with very few observations each. This is especially common in binary data with continuous predictors. The Hosmer-Lemeshow test is more appropriate in this situation.

Real Overdispersion

Real overdispersion occurs when there is more variability in the data than the binomial model predicts. A common cause is clustering of observations, for example patients within the same hospital may have correlated outcomes. Real overdispersion can be addressed by adjusting standard errors using a dispersion parameter or by using models that account for clustering (e.g., GEE, mixed models).

Detecting Overdispersion

Overdispersion can be detected when the ratio of the Pearson χ² (or deviance) to its degrees of freedom substantially exceeds 1. For grouped data, this ratio should be close to 1 if the model fits well. Values much greater than 1 suggest overdispersion, while values much less than 1 may suggest underdispersion or a model that is too complex.

Pseudo-R² and Influential Observations

Pseudo-R² measures (e.g., McFadden’s, Cox-Snell, Nagelkerke) provide an indication of how much of the variation in the outcome is explained by the model. They are analogues of R² in linear regression but are not directly comparable. Values tend to be lower for logistic regression than for linear regression.

Influential observations can be identified using several diagnostic measures: outliers (large residuals), leverage (unusual covariate patterns), delta-betas (influence on individual coefficients), delta-χ², and delta-deviance (influence on overall fit). These diagnostics help identify observations that disproportionately affect the model.

📊 Example: Birth Weight Model Evaluation

Returning to the low birth weight example, suppose the fitted model has an AUC of 0.623. This indicates limited predictive ability: the model does only marginally better than chance at discriminating between low and normal birth weight infants. This does not necessarily mean the model is useless for understanding risk factors; it simply means the included predictors explain only a small portion of the variation in birth weight outcomes.

Knowledge check: this section

1. What does the Hosmer-Lemeshow test evaluate?

The Hosmer-Lemeshow test groups observations by predicted probability (typically into deciles) and compares observed and expected outcomes within each group. A non-significant P-value suggests the model fits the data adequately.

2. What does an ROC curve AUC of 0.5 indicate?

An AUC of 0.5 corresponds to the 45-degree diagonal on the ROC curve, meaning the model performs no better than random classification. An AUC of 1.0 would indicate perfect discrimination.

3. The minimum sample size rule for logistic regression suggests:

The rule of thumb is to have at least 10(k + 1) positive outcomes (events), where k is the number of predictors. This ensures stable coefficient estimates and reliable model performance. Having fewer events risks overfitting and biased estimates.

✎ Reflection

Consider a logistic regression model you have encountered (or might build). How would you evaluate whether the model has adequate goodness of fit and predictive ability? Which diagnostics would be most important to check?

Model answerGoodness-of-fit evaluation: (a) Hosmer-Lemeshow test: partitions predictions into deciles and compares observed vs. expected counts; high p-value indicates good fit (no evidence of misfit); but note: large samples make the test reject even trivial misfit. (b) Calibration plot: plot observed proportion vs. predicted probability across deciles; should be on the 45° line. (c) Brier score. Predictive ability: (a) AUC (C-statistic): probability that a random case has higher predicted probability than a random non-case; 0.7–0.8 acceptable, > 0.8 good, > 0.9 excellent. (b) Sensitivity, specificity, PPV, NPV at the optimal threshold. (c) Decision-curve analysis for clinical utility. (d) Calibration-in-the-large (mean predicted vs. observed event rate). The most important: calibration plot (for use in clinical decision-making) and AUC (for discrimination).
✓ Reflection saved!
Complete the quiz and reflection to continue.
Section 8 of 13

GLMs, Exact & Conditional Logistic Regression

⏱ Estimated time: 20 minutes
Section 4 of 4

Generalised Linear Models, Exact & Conditional Logistic Regression

Placing logistic regression in a wider family, and two specialised versions for small or matched data.

The unifying frame

Two choices define a generalised linear model

Data typeDistributionLinkModel
ContinuousNormalIdentityLinear
BinaryBinomialLogitLogistic
CountPoissonLogPoisson
Count (overdispersed)Negative binomialLogNB
Refinements

Canonical links, alternatives, and fitting

  • The canonical link is the natural default for each distribution; the logit for binary data.
  • Other links exist: probit and complementary log-log for binary outcomes.
  • All are fitted by maximum likelihood, via iterative routines (Newton-Raphson, iteratively reweighted least squares).
  • Quasi-likelihood needs only the mean-variance relationship, not a full distribution.
Special case 1

Exact logistic regression for small or sparse data

Ordinary logistic regression assumes a large sample. When data are tiny, severely unbalanced, or show perfect prediction (a predictor separates the outcome and pushes a coefficient toward infinity), the usual estimates break down.

Exact logistic regression uses conditional maximum likelihood for exact p-values and intervals without large-sample theory. Firth's penalised-likelihood method (1993) reduces small-sample bias and handles separation gracefully.Firth (1993)
When to use it

Reach for exact methods when…

  • the sample size is very small;
  • the data are severely unbalanced (very few events or non-events);
  • perfect prediction occurs and an estimate runs to infinity;
  • standard maximum likelihood fails to converge.

Trade-off: computationally intensive, often impractical with many predictors.

Special case 2

Conditional logistic regression for matched data

In a matched case-control study you pair each case with controls sharing features like age and sex. Handling that with ordinary logistic regression and one indicator per matched set causes two problems:

Too many parameters

Their number grows with the number of matched sets.

Biased estimates

Especially with small strata.

A conditional likelihood (Eq 16.17) removes the per-set intercepts, giving unbiased odds ratios for the predictors of interest.

Limitations and the choice

What conditional logistic regression gives up

  • No intercept is estimated.
  • No coefficient for variables constant within a set, including the matching factors.
  • Only outcome-varying matched sets contribute; concordant sets drop out.
  • Predicted probabilities cannot be computed directly.

Standard

Adequate sample, events not rare, unmatched.

Exact

Very small, unbalanced, or perfect prediction.

Conditional

Matched case-control designs.

Lesson recap

What we covered, and what's next

From the failure of linear regression on binary outcomes, to the log-odds model and odds ratios, to testing and interpreting coefficients, to evaluating fit and prediction, to the wider family of generalised linear models with exact and conditional variants.

Next: a short reflection on a logistic model in your own field, then the knowledge check to consolidate the lesson.

Introduction and Overview

Earlier sections covered standard logistic regression. This section places it in a wider context. Logistic regression is one example of the generalised linear model (GLM) family, which also includes the linear, Poisson, and other regressions you'll meet later in this course. The section closes with exact logistic regression, the small-sample alternative when standard maximum-likelihood methods fail.

Learning Objectives

  • Define a generalised linear model in terms of its random component, link function, and linear predictor.
  • Place logistic, linear, Poisson, and negative binomial regression within the GLM family.
  • Identify situations (small samples, sparse cells, perfect prediction), where exact logistic regression is preferred.
  • Explain when conditional logistic regression should be used for matched case-control data.

Generalised Linear Models (GLMs)

Logistic regression is a member of the broader family of Generalised Linear Models (GLMs). A GLM is defined by two key components: (1) a link function that relates the expected value of the outcome to the linear combination of predictors, and (2) the distribution of the outcome variable.

Data TypeDistributionCanonical LinkExample
ContinuousGaussian (Normal)IdentityLinear regression
BinaryBinomialLogitLogistic regression
CountPoissonLogPoisson regression
Count (overdispersed)Negative BinomialLogNB regression

The canonical link is the “natural” link function for each distribution. For binary data, the canonical link is the logit. Non-canonical links (e.g., probit, complementary log-log for binary data) can also be used. GLMs are estimated using maximum likelihood, often with iterative algorithms such as Newton-Raphson or iteratively reweighted least squares. Quasi-likelihood estimation can be used when the full distribution is not specified, requiring only the mean-variance relationship.

Exact Logistic Regression

Standard logistic regression relies on large-sample approximations. When the dataset is very small or severely unbalanced (e.g., very few events), these approximations may be poor, and ML estimates can be biased or fail to converge. Exact logistic regression uses conditional maximum likelihood to produce exact P-values and confidence intervals without relying on large-sample theory. A widely used alternative is the penalised-likelihood approach of Firth (1993), which reduces small-sample bias and handles separation gracefully.

When to Use Exact Logistic Regression

Exact logistic regression is preferred when:

  • The sample size is very small
  • The data are severely unbalanced (very few events or non-events)
  • Perfect prediction occurs (a predictor perfectly separates outcomes, causing ML estimates to be infinite)
  • Standard ML estimation fails to converge

The trade-off is that exact methods are computationally intensive and may not be feasible for models with many predictors.

Conditional Logistic Regression for Matched Data

Conditional logistic regression is used for matched case-control studies. In matched designs, using unconditional logistic regression with stratum (matched set) indicators is problematic because: (1) the number of parameters grows with the number of matched sets, and (2) coefficient estimates can be biased, especially with small strata.

Conditional logistic regression solves this by using a conditional likelihood (Eq 16.17) that eliminates the stratum-specific intercept parameters from the estimation. This produces unbiased estimates of the odds ratios for the predictors of interest without needing to estimate the matching parameters.

Limitations of Conditional Logistic Regression

Conditional logistic regression has several limitations:

  • No intercept is estimated (it is conditioned out along with all stratum-specific effects)
  • Coefficients cannot be estimated for variables that are constant within matched sets (e.g., the matching factors themselves)
  • Only matched sets with variation in the outcome contribute to the likelihood (concordant sets are uninformative)
  • Predicted probabilities cannot be computed directly (since there is no intercept)
Link FunctionClick to explore
DistributionClick to explore
Conditional LikelihoodClick to explore

When to Use Which Approach

Standard logistic regression: Use when the sample size is adequate, events are not extremely rare, and data are not matched.<br>Exact logistic regression: Use when the sample is very small, data are severely unbalanced, or perfect prediction occurs.<br>Conditional logistic regression: Use for matched case-control studies where stratum-specific parameters would be problematic to estimate.

Knowledge check: this section

1. In the GLM framework, what are the two key components that must be specified?

A GLM requires specification of two components: (1) the link function, which relates the expected value of the outcome to the linear predictor, and (2) the distribution of the outcome variable (e.g., Gaussian, Binomial, Poisson).

2. When is exact logistic regression preferred over standard logistic regression?

Exact logistic regression is preferred when the sample is very small, the data are severely unbalanced (very few events), or when perfect prediction occurs. In these situations, standard ML estimates may be biased or fail to converge because large-sample approximations are unreliable.

3. In conditional logistic regression for matched data, why is the intercept not estimated?

The conditional likelihood conditions on the number of cases within each matched set, which eliminates the stratum-specific intercept parameters. This avoids the incidental parameter problem and produces unbiased OR estimates, but means predicted probabilities cannot be computed directly.

✎ Reflection

Think about a study design in your field that uses matching (e.g., matched case-control). Why would conditional logistic regression be more appropriate than unconditional logistic regression for analysing such data? What information would be lost by using the conditional approach?

Model answerIn a matched case-control study (e.g., 1:1 matching on age, sex, and admission date), each matched set is a stratum. Unconditional logistic regression treats observations as independent and ignores the matched structure; this gives biased odds-ratio estimates because the matching variables are perfectly balanced by design but the analysis tries to estimate them as covariates. Conditional logistic regression uses the within-stratum likelihood (conditioning on the matched-set total), effectively cancelling out any stratum-level effects (including the matching variables and any unmeasured stratum-level confounders). What's lost: you cannot estimate the effect of the matching variables themselves (they're absorbed into the strata), so if you wanted the main effect of age or sex on the outcome, conditional logistic is the wrong model. Practical rule: match on what you don't want to estimate; analyse with conditional logistic regression.
✓ Reflection saved!
Complete the quiz and reflection to continue.
Section 9 of 13

Introduction & Steps in Model Building

⏱ Estimated time: 20 minutes
Lesson 3 · Part 3 · HSCI 410

Model-Building Strategies

How to build a defensible regression model when many candidate variables compete for a place.

The central idea

Decisions before data

Model building is a sequence of principled choices made before the data are searched for patterns.

Automated selection overfits and misleads. Subject-matter knowledge and causal structure are the foundation. Statistical criteria confirm or refine, they do not replace, that foundation.

Section 1 of 4

Introduction & Steps in Model Building

Two goals, a six-step workflow, and the causal diagram that comes before everything else.

Two goals

Prediction versus causal explanation

Prediction

Maximise accuracy on new data. Uncertain variables are often kept. Coefficient interpretation is secondary. Report against the TRIPOD checklist (Collins et al., 2015).

Causal explanation

Precise, unbiased estimates for the variables of interest. Confounders retained regardless of significance. Mediators excluded when estimating total effects.

Six steps

The model-building workflow

1. Maximummodel 2. Selectioncriteria 3. Selectionstrategy 4. Conductanalyses 5. Reliabilitycheck 6. Presentresults
Before Step 1

The causal diagram comes first

Draw the proposed relationships before touching the data. The diagram classifies every variable as a confounder, mediator, or neither.

Exposure (X) Outcome (Y) Confounder (C) Mediator (M)

Confounders: retain always. Mediators: exclude when estimating the total effect of X on Y.

A worked example

Smoking, birth weight, and the mediator trap

Exclude from the model

Gestation length and weight gain during pregnancy are mediators. Including them removes the indirect effect of smoking on birth weight.

Retain regardless

Race and maternal education are likely confounders. They must stay in the model even if not statistically significant.

Carry forward

Two kinds of knowledge, working together

  • Goal first: prediction and causal explanation require different strategies.
  • Draw the causal diagram before any data analysis; classify every variable.
  • Confounders stay; mediators leave when estimating total effects.
  • Statistical criteria confirm decisions they do not make them.

Introduction and Overview

An earlier lesson walked through linear regression with a fixed set of predictors. Real data rarely arrive with a clean “here are the four predictors you should use” instruction. This lesson turns to the broader question of how to build a defensible model when you have many candidate predictors and need to decide which to include. The four content sections move from goals and frameworks (this section), to reducing predictors and handling missing values (a later section), to modelling continuous predictor–outcome relationships flexibly with categorisation, polynomials, and splines (a later section), and finally to interactions, moderation, and selection criteria (a later section). Throughout, the central tension is between data-driven flexibility and theory-driven discipline, and the answer is usually closer to theory than the data alone would suggest (Babyak, 2004; Heinze, Wallisch, & Dunkler, 2018).

Learning Objectives

  • Distinguish prediction-focused from causal-explanation model-building goals and explain how each shapes the strategy.
  • Outline the steps in building a regression model from candidate predictors through final reporting.
  • Use a causal diagram to identify the predictors that must be retained regardless of statistical significance.
  • Recognise when subject-matter knowledge should override what the data alone seem to suggest.

Why Model-Building Strategies Matter

When building a regression model, we need to decide on the goals of the analysis, incorporate both statistical considerations and subject matter knowledge, and balance the desire for parsimony (simplicity) with the desire for a model that “best fits” the data. The definition of “best fit” depends on the goal of the analysis, and the principles discussed in this chapter apply to all types of regression models.

Key Concept

Regression models are generally built to meet one of two broad objectives: (1) to build the best model for predicting future observations, or (2) to understand the causal relationship(s) between predictors and the outcome. The approach to model building differs depending on which goal you are pursuing.

Goals of the Analysis

If the goal is prediction, we want to keep any variables whose relationship with the dependent variable is questionable, because excluding them might lead to inaccurate predictions when future observations have extreme values for those variables. The details of specific predictors are of little consequence; we just want overall accuracy. Reporting guidelines such as TRIPOD (Collins, Reitsma, Altman, & Moons, 2015) provide a checklist for transparently documenting prediction models.

If the goal is understanding biological relationships, we want precise estimates of coefficients for the variables of interest. Careful attention must be paid to interaction and confounding effects. Factors likely to be confounders should be retained in the model regardless of statistical significance, while factors that are almost certainly not confounders should generally be excluded, especially if they are intervening variables, as their inclusion may bias results.

Prediction GoalClick to explore
Causal UnderstandingClick to explore
Parsimony vs FitClick to explore

Steps in Building a Regression Model

The process of building a regression model follows a systematic set of steps. While statistical software handles the computation, the researcher must make many decisions along the way that require both subject matter expertise and statistical reasoning.

Step 1: Specify the Maximum Model

Identify the outcome variable and determine whether it needs transformation (e.g., natural log). Then identify the full set of predictors to consider. The maximum model includes all possible predictors of interest. While a large model prevents overlooking important predictors, adding too many increases the risks of collinearity and spurious associations. Key sub-steps include: drawing a causal diagram, potentially reducing predictors, considering missing values, evaluating effects of continuous predictors, and deciding on interaction terms.

Step 2: Specify the Selection Criteria

Decide how you will determine which variables to retain. Criteria can be non-statistical (e.g., is it a primary predictor of interest? Is it a known confounder?) or statistical (e.g., partial F-tests, likelihood-ratio tests, information criteria like AIC or BIC). Both types of criteria should be considered together.

Step 3: Specify the Selection Strategy

Choose how to apply the criteria. Options include: examining all possible subsets, forward selection (adding variables one at a time), backward elimination (starting with all variables and removing), or stepwise procedures (combining forward and backward). The strategy determines the order in which variables are evaluated.

Steps 4–6: Conduct, Evaluate, and Present

Step 4: Conduct the analyses using your chosen strategy and criteria. Step 5: Evaluate the reliability of the chosen model using diagnostics and sensitivity analyses. Step 6: Present the results in a meaningful way, ensuring they are interpretable to your audience and that the model-building process is transparent.

Building a Causal Model

Before beginning the model-building process, it is imperative to have a causal model in place, usually presented as a causal diagram. The diagram identifies potential causal relationships among the predictors and the outcome of interest.

📋 Example: Cigarette Smoking and Birth Weight

Suppose you want to study the effects of cigarette smoking on birth weight, and you also have data on the mother’s race, education level, total birth order, gestation length, number of babies born, and weight gain during pregnancy.

A causal diagram would show that gestation length and weight gain are intervening variables; they lie on the causal pathway between smoking and birth weight. If the objective is to quantify the total effect of smoking on birth weight, you would not include gestation length or weight gain in the model, because doing so would remove the effect of smoking that is mediated through them.

On the other hand, race and college education might be confounders and should be retained regardless of statistical significance. Building the causal diagram first helps ensure you do not accidentally adjust for intervening variables.

⚠ Important Distinction

Confounders should be retained in the model to avoid bias. Intervening variables should generally be excluded when estimating total effects, because including them removes the indirect effect that passes through them. A causal diagram drawn before model building helps you distinguish between the two.

Knowledge check: this section

1. When the goal of a regression model is to understand biological relationships, which of the following is true?

When the goal is causal understanding, confounders should be retained regardless of significance to avoid biased estimates. Intervening variables should generally be excluded when estimating total effects.

2. What is the first step in building a regression model?

The first step is to specify the maximum model: identify the outcome variable and the full set of predictors to consider. This includes drawing a causal diagram and determining whether transformations are needed.

3. In a study of cigarette smoking’s effect on birth weight, why should gestation length generally NOT be included in the model?

Gestation length is an intervening variable: smoking affects gestation length, which in turn affects birth weight. Including it would remove the indirect effect of smoking that is mediated through gestation length, underestimating the total effect.

✎ Reflection

Think about a research question in your own field. What would the causal diagram look like? How would you distinguish confounders from intervening variables?

Model answerFor shift work and metabolic syndrome: confounders are causes of both exposure (shift work) and outcome (metabolic syndrome) that exist temporally before shift work was chosen: age, SES, education, occupational sector, family history. Intervening variables are on the causal pathway from shift work to metabolic syndrome: circadian disruption, sleep duration, dietary timing, physical activity during shifts, weight gain during the employment period. The DAG distinguishes them visually: a variable with an arrow from itself into both exposure and outcome is a confounder; a variable with arrows from exposure into it and then into outcome is a mediator. Confounders must be adjusted for to estimate the causal effect; mediators must NOT be adjusted for to estimate the total effect (they should be examined separately in mediation analysis if the indirect path is the question).
✓ Reflection saved!
Complete the quiz and reflection to continue.
Section 10 of 13

Reducing Predictors & Missing Values

⏱ Estimated time: 25 minutes
Section 2 of 4

Reducing Predictors & Missing Values

Principled predictor reduction and missing-data strategies that match the missingness mechanism.

Screening first

Descriptive and correlation screening

Protected variables: primary predictors and known confounders are never eliminated. Reduction applies to the rest.

Descriptive screening

Remove variables with near-zero variance, many missing values, or sparse categories. They add noise.

Correlation screening

Pairs with correlation above roughly 0.9 are redundant. Keep the one with stronger biological rationale or fewer missing values.

Combining predictors

Indices and Cronbach's alpha

Related predictors can be collapsed into a single index. Cronbach's alpha checks whether the items are measuring the same construct.

< 0.60Unacceptable
0.66–0.70Minimally acceptable
0.71–0.80Respectable
> 0.90Consider shortening
Liberal screening

Screening on unconditional associations

The method

Keep predictors whose simple one-at-a-time association with the outcome is significant at a liberal threshold (p < 0.15 or 0.20), screened with univariable regressions.

The drawback

A real predictor can be masked by confounding and screened out. Mitigate with the liberal threshold, and add excluded predictors back one at a time at the end.

Dimension reduction

PCA, factor analysis, correspondence analysis

PCA

Converts predictors to orthogonal components ranked by variance explained. Eliminates multicollinearity.

Factor analysis

Similar to PCA, but assumes factors carry inherent meaning. Items with high loadings are flagged as important.

Correspondence analysis

For categorical variables. Produces a two-dimensional map of predictor–outcome clusters.

Missing data

Three mechanisms, three consequences

MCAR

Missing completely at random. Complete case analysis is unbiased but imprecise.

MAR

Missingness depends on observed data. Multiple imputation corrects bias under this assumption.

MNAR

Missingness depends on the unobserved value. No standard method fully corrects the bias.

Carry forward

Multiple imputation: why it matters

Multiple imputation generates several filled-in datasets, analyses each, and combines results. That combining step captures the uncertainty from missing data.

  • Single imputation underestimates uncertainty; avoid it.
  • Maximum likelihood and Bayesian estimation also make missingness ignorable under MAR.
  • A later section asks: once a predictor is in the model, what functional form should it take?

Introduction and Overview

An earlier section settled the conceptual goals and the workflow. This section turns to two practical issues that determine which predictors actually make it into the final model. First: when you have more candidate predictors than your sample can support, how do you reduce the set without introducing bias? Second: missing values reduce your effective sample further. How should you handle them?

Learning Objectives

  • Apply principled techniques (variable clustering, prior knowledge, dimension reduction) to shrink a long candidate-predictor list.
  • Critique purely automated (stepwise) selection and explain why it produces fragile models.
  • Distinguish complete-case analysis, single imputation, and multiple imputation, and choose between them based on the missing-data mechanism.
  • Document predictor reductions and missing-value decisions so the final model is reproducible.

Reducing the Number of Predictors

It is sometimes necessary to reduce the number of predictors in the model-building process. Before undertaking any reduction, it is essential to identify the primary variables of interest and any variables that might be confounders or interacting variables; these should always be retained for consideration.

Practical Tip

The most appropriate procedure for managing a large number of predictors is often to design a more focused study that collects high-quality data on fewer predictors. This greatly reduces the risk of identifying spurious associations.

🎲 Interactive: Overfitting & the Bias–Variance Tradeoff (Babyak, 2004)

Fit polynomials of increasing degree to a small training sample, then evaluate on a fresh hold-out sample drawn from the same true relationship. In-sample R² always rises with more flexibility, but out-of-sample error has a U-shape. The minimum is the sweet spot.

Training data + fitted curve
In-sample R² vs out-of-sample MSE by degree
Training R²
Test MSE
Training MSE
Optimal degree
Try this: with n=20 and σ=0.5, slide the degree from 1 to 14. Watch training R² climb monotonically, while test MSE drops, hits a minimum, then explodes. The model with the lowest test MSE is the right answer, not the one with the highest R².

Screening Predictors Based on Descriptive Statistics

Before starting any model building, become thoroughly familiar with your data using descriptive statistics (means, variances, percentiles for continuous variables; frequency tabulations for categorical variables). This helps identify variables of little value. Guidelines include:

  • Avoid variables with large numbers of missing observations
  • Select only variables with substantial variability (e.g., if almost all subjects are male, sex will not be a useful predictor)
  • If a categorical variable has many categories with small counts, consider combining categories or eliminating the variable

Correlation Analysis

Examining pairwise correlations among predictor variables identifies pairs that contain essentially the same information. Highly correlated predictors (typically r > 0.9) produce multicollinearity, leading to unstable coefficient estimates and incorrect standard errors.

If highly correlated pairs are found, select one based on criteria such as biological plausibility, ease of measurement, and fewer missing values. Note that pairwise screening will not detect multicollinearity arising from linear combinations of multiple predictors.

Creation of Indices & Cronbach’s Alpha

Related predictors can sometimes be combined into a single index. For example, the Hamilton Rating Scale for Depression combines 22 characteristics into an overall depression score.

Cronbach’s alpha evaluates the internal consistency of such a scale: how well each predictor correlates with the overall scale. Interpretation guidelines:

  • < 0.60: Unacceptable
  • 0.60–0.65: Undesirable
  • 0.66–0.70: Minimally acceptable
  • 0.71–0.80: Respectable
  • 0.81–0.90: Very good
  • > 0.90: Consider shortening the scale

One drawback of indices is that they preclude evaluating the effects of the individual factors that were combined.

Screening Variables Based on Unconditional Associations

A common approach is to select only predictors with unconditional associations significant at a liberal P-value (e.g., 0.15 or 0.20). Simple univariable regression models are used for this screening.

One drawback: an important predictor might be excluded if its effect is masked by another variable (i.e., confounding is present). Using a liberal P-value helps prevent this. Another approach is to build the model with significant predictors, then add back excluded predictors one at a time to check if any become significant after adjusting for other variables.

PCA, Factor Analysis & Correspondence Analysis

Principal Components Analysis (PCA) converts a set of k predictor variables into k orthogonal (uncorrelated) principal components, each containing a decreasing proportion of total variation. A small subset of components is then used as predictors, eliminating multicollinearity. Coefficients can be back-transformed to the original predictors, though interpretation is less direct.

Factor analysis is similar but assumes factors with inherent meaning can be created from the original variables. Unlike PCA, the composition of factors varies as the number selected changes. Predictors with high “factor loadings” are identified as important determinants.

Correspondence analysis is designed for categorical variables. It produces a visual summary (2D scatterplot) of complex relationships, showing which clusters of predictors are associated with which clusters of outcome values.

The Problem of Missing Values

Missing data are common in observational studies. Statistical programs use complete case analysis by default: only observations with no missing values for any variable are included. Even a relatively low overall percentage of missing values can result in a substantial reduction of the sample if missing data are spread across observations.

MCARClick to explore
MARClick to explore
MNARClick to explore

Dealing with Missing Data: Imputation

The two main alternatives to complete case analysis are imputation and analysis methods where missing data are ignorable. Imputation involves replacing missing data points with values predicted from available data.

Single vs Multiple Imputation

Single imputation derives one estimate for each missing value. However, analysis based on single imputed data does not account for the uncertainty of the estimated values. Multiple imputation generates multiple imputed datasets and combines results, properly accounting for this uncertainty. Multiple imputation is generally preferred over single imputation.

Maximum Likelihood & Bayesian Estimation

Maximum likelihood (ML) and Bayesian estimation are procedures that make missing values ignorable under the MAR assumption. ML requires specification of the distribution of missing values for predictors, but this is unnecessary for outcome missing values. These methods are closely linked to multiple imputation conceptually.

Knowledge check: this section

1. What does Cronbach’s alpha measure?

Cronbach’s alpha evaluates the internal consistency of a scale: how well each individual predictor (item) correlates with the overall scale. It is used to assess the reliability of combining related predictors into a single index.

2. Under which missing data mechanism is complete case analysis most likely to produce biased results?

Under MCAR, complete case analysis produces unbiased estimates (though with reduced power). Under MAR and MNAR, complete cases may not be representative of the full sample, leading to biased estimates. MNAR is the most problematic because the missingness depends on the unobserved data itself.

3. Why is multiple imputation generally preferred over single imputation?

Multiple imputation generates multiple completed datasets and combines results, which properly reflects the uncertainty associated with the imputed values. Single imputation treats imputed values as if they were known, underestimating the true variability in the data.

✎ Reflection

Consider a dataset you have worked with (or imagine one). Which type of missing data mechanism (MCAR, MAR, MNAR) do you think was most likely present, and why? What approach would you take to handle it?

Model answerFor a cohort study with 15% missing covariates: most likely MAR (missing at random conditional on observed variables): missingness is related to observed factors like age, education, or visit type but, after conditioning on them, unrelated to the unobserved values. Less commonly MCAR (truly random, rare in real data). MNAR (missing not at random) is possible if dropout is correlated with unmeasured factors like worsening health. Approach: (a) characterise the missingness pattern by tabulating missing-vs-observed against observed covariates; (b) under MAR, use multiple imputation by chained equations (MICE) with 20–50 imputations, incorporating all observed analysis-relevant variables in the imputation model; (c) run sensitivity analyses under plausible MNAR scenarios (delta-method adjustment); (d) compare complete-case analysis to imputed estimates; large discrepancies suggest MAR/MNAR concerns. Never use mean imputation.
✓ Reflection saved!
Complete the quiz and reflection to continue.
Section 11 of 13

Effects of Continuous Predictors

⏱ Estimated time: 25 minutes
Section 3 of 4

Effects of Continuous Predictors

Scatterplots, smoothers, categorisation, polynomials, fractional polynomials, and splines.

Visualising first

Scatterplots and smoothed lines

A smoothed line reveals the shape of the predictor–outcome relationship without imposing a parametric form.

Continuous predictor Outcome Smoothed Linear fit
Categorisation

When it helps, when it hurts

Potential use

Avoids the linearity assumption. About five categories suffices to control for confounding effects.

The costs

Discards within-category variation. Cutpoints are arbitrary. Data-driven cutpoints bias results. Biological relationships are rarely step-functions.

Polynomial models

Integer and fractional powers

Adding power terms allows the regression line to curve. Centring the predictor before squaring it reduces collinearity between the original variable and its powers.

Quadratic (centred)
\[ \color{#0B7B6B}{Y} = \color{#C2410C}{\beta_0} + \color{#6D28D9}{\beta_1}(x - \bar{x}) + \color{#047857}{\beta_2}(x - \bar{x})^2 + \color{#BE185D}{\varepsilon} \]
Y outcome β₀ intercept β₁ linear coefficient β₂ quadratic coefficient ε error

Fractional polynomials allow powers from the set \(\{-3,\,-2,\,-1,\,-0.5,\,0,\,0.5,\,1,\,2,\,3\}\), where power 0 means the natural log. Very flexible with few terms; present the fitted curve graphically.

Splines

Piecewise smooth functions

knot 1 knot 2 Cubic spline Linear spline

Knots placed at the 25th, 50th, and 75th percentiles in the absence of prior evidence. Restricted cubic splines constrain the tails to be linear.

Carry forward

Which approach to choose

Inspect first

Always plot the predictor against the outcome with a smoother before modelling. The shape guides the choice.

Preferred in practice

Restricted cubic splines are well-behaved at the tails and flexible. Fractional polynomials are compact. Both beat naive categorisation.

Introduction and Overview

An earlier section reduced your candidate-predictor list. This section zooms into how to model the predictors that survived, specifically the continuous ones. Linear regression assumes a linear relationship between predictor and outcome by default, but real relationships are often curved. Categorisation, polynomials, and splines are three different ways to allow curvature; each has its own trade-offs.

Learning Objectives

  • Use scatterplots and smoothed lines (e.g., LOESS) to inspect the shape of predictor–outcome relationships before modelling.
  • Decide when categorising a continuous predictor helps interpretation and when it discards too much information.
  • Fit polynomial terms to capture simple curvature, and recognise their limits at the tails of the data.
  • Use splines (linear, restricted cubic) to model flexible non-linear relationships without losing interpretability.
  • Compare these approaches and choose one based on the analytic question, sample size, and audience.

Evaluating Continuous Predictor–Outcome Relationships

It is important to evaluate the structure of the relationship between a continuous predictor and the outcome before starting model building. The underlying assumption of linearity can be evaluated through diagnostics after fitting the model, but it is useful to explore the nature of the relationship beforehand.

Key Approaches

Four main approaches to evaluating the effect of continuous predictors are: (1) scatterplots and smoothed line plots, (2) categorising the continuous variable, (3) exploring polynomial models, and (4) using splines.

Scatterplots & Smoothed Lines

Scatterplots are 2-way plots of the outcome (Y-axis) versus the continuous predictor (X-axis). They are most useful for continuous outcomes; scatterplots of dichotomous outcomes present as two lines of dots and are rarely informative by themselves.

Scatterplots can be greatly improved by adding a smoothed line through the centre of the data. All smoothed lines have a local-influence property: the position of the line at any value of x is influenced by nearby points but not by distant points.

Types of Smoothed Lines

There are several types of smoothed line functions:

  • Running mean smoother: Computes a simple average of y values in the neighbourhood
  • Running line smoother: Fits a simple linear regression through observations in the neighbourhood
  • Lowess smoother: Fits a weighted linear regression where points closer to xi receive larger weight (using tricube weighting)
  • Local polynomial smoother: Fits a weighted polynomial regression in the neighbourhood

The bandwidth controls the size of the neighbourhood. A bandwidth of 0.8 means 80% of the data is used for each point. Larger bandwidths produce smoother lines but may miss important features.

Caution with Extreme Values

All smoothed line functions can have problems at the extreme values of the predictor distribution. This is because the neighbourhood at the tails is not symmetrical and contains relatively few data points. It is important not to pay much attention to the extremes of the fitted line. Vertical dashed lines marking the 2.5th and 97.5th percentiles can help delineate where most of the data falls.

Categorising Continuous Predictors

The assumption of linearity can be avoided by converting the continuous predictor into categories. However, this is generally not advisable for three reasons:

  1. Categorisation involves the loss of information
  2. It is unlikely that biological processes have a step-function relationship (i.e., sudden changes at specific cutpoints)
  3. The choice of cutpoints is arbitrary and, if data-driven, may lead to biased results

That said, about 5 categories will usually suffice to control for confounding effects. A model with a categorised variable can be compared to one with a continuous (linear) variable using AIC or BIC.

Polynomial Models

Polynomials allow the regression line to follow a curve rather than a straight line. Power terms (e.g., x² or x³) are added to the model. Unlike smoothed lines, polynomial models have a global-influence property: the shape of the entire line is influenced by all the data.

Quadratic model
\[ \color{#0B7B6B}{Y} = \color{#C2410C}{\beta_0} + \color{#6D28D9}{\beta_1} \color{#1D4ED8}{x} + \color{#047857}{\beta_2} \color{#1D4ED8}{x}^2 + \color{#BE185D}{\varepsilon} \]
The outcome is the intercept plus a linear term in the predictor plus a quadratic term in its square, allowing a curved relationship, plus error.

⚠ Centring to Avoid Collinearity

The original variable (x) is often highly correlated with its squared term (x²), creating collinearity. The solution is to centre the variable by subtracting the mean before squaring. If a quadratic model is insufficient (i.e., the quadratic term is significant but the fit is still poor), a cubic term (x³) can be added.

Fractional Polynomials

Fractional polynomials (FPs) extend the idea of polynomial models by allowing power terms that are not restricted to positive integers. The most common set of powers to consider is: −3, −2, −1, −0.5, 0 (= ln), 0.5, 1, 2, 3. A 2-degree FP can fit a wide range of non-linear shapes and may be the most parsimonious way to model non-linearity.

📊 Example: Birth Weight vs Gestation Length

A quadratic model regressing birth weight on centred gestation length showed R² = 0.29. When fractional polynomials were explored, the best-fitting 2-degree FP used powers of 3 and 3×ln(gest), yielding R² = 0.30 and fitting significantly better than the linear, quadratic, or cubic models. The FP coefficients are not directly interpretable; the only way to make sense of such a model is to display the function graphically.

Splines

An alternative to polynomial models is to fit a piecewise linear function. Points where the slope changes are called knot points. In the absence of prior evidence, knots may be chosen at percentiles of the predictor (e.g., 25th, 50th, 75th). Cubic splines allow for smoother transitions across knots compared to linear splines, producing more biologically plausible curves; the same logic extends to generalised additive models (Hastie & Tibshirani, 1986).

ApproachInfluenceStrengthsLimitations
Smoothed linesLocalFlexible; reveals non-linearityCannot be used in model itself; issues at extremes
CategorisationN/AAvoids linearity assumptionLoses information; arbitrary cutpoints
PolynomialsGlobalSimple to implement; formal testsMay over-fit at extremes; collinearity
Fractional polynomialsGlobalVery flexible with few termsCoefficients not directly interpretable
SplinesLocalFlexible; smooth transitionsSudden shifts at knots (linear splines)
Knowledge check: this section

1. Why is categorising a continuous predictor generally not advisable?

Categorisation loses information about the continuous variable, assumes an unlikely step-function relationship between the predictor and outcome, and involves arbitrary cutpoint choices. However, about 5 categories can suffice to control for confounding.

2. What is a key difference between smoothed lines and polynomial models?

Smoothed lines have a local-influence property: the line at any point is influenced primarily by nearby data. Polynomial models have a global-influence property: the entire curve is influenced by all data points. This means polynomials can be heavily influenced by extreme values.

3. Why should you centre a continuous variable before adding its squared term to a regression model?

The original variable (x) is often highly correlated with its squared term (x²), leading to collinearity. Centring (subtracting the mean) before squaring reduces this correlation and produces more stable coefficient estimates.

✎ Reflection

Think about a continuous predictor in your field. Would you expect the relationship with the outcome to be linear? If not, which approach (categorisation, polynomials, fractional polynomials, or splines) would you choose and why?

Model answerFor age vs. all-cause mortality, the relationship is decidedly non-linear: risk accelerates with age. Choice: restricted cubic splines (3–5 knots placed at percentiles of the age distribution) are typically best because they (a) capture non-linearity flexibly without forcing a specific functional form, (b) are stable at the edges of the data (unlike polynomials, which can have wild tails), and (c) yield interpretable plots of the dose-response. Categorisation is the worst choice (information loss, threshold effects, instability of effect at the cut-point); polynomials work for simple curves but extrapolate badly; fractional polynomials are a compromise (data-driven choice of exponents) but less interpretable than splines. The right defence is to plot the spline fit overlaid on the data and present the dose-response curve as a deliverable rather than only regression coefficients.
✓ Reflection saved!
Complete the quiz and reflection to continue.
Section 12 of 13

Interactions & Building the Model

⏱ Estimated time: 25 minutes
Section 4 of 4

Interactions & Building the Model

Interaction specification, moderation, model-selection criteria, and selection strategies.

Interaction specification

Five strategies for two-way interactions

All pairs (small p)
Significant main effects only
Significant unconditional assoc.
Biologically motivated pairs
Exposure × covariate only

Rule: if an interaction is in the model, both constituent main effects must be included. Bonferroni adjustment is warranted when many interactions are tested.

Moderation

Statistical interaction with a substantive story

Mediation (from DAG)

X acts through M to reach Y. Answers: through what?

Moderation (interaction)

W changes the strength of the X → Y relationship. Answers: for whom, or under what conditions?

A p-value detects an interaction. Only subject-matter knowledge supplies the story that makes it worth keeping.

Moderation in R

Does maternal age modify the smoking effect?

The test

lm(bwt ~ smoke * age) versus the main-effects model, compared with a partial F-test: F = 4.11, p = 0.044. The interaction earns its place.

The follow-up

interact_plot() draws two non-parallel age slopes; sim_slopes() with Johnson-Neyman shows where the smoking effect is statistically meaningful.

Selection criteria

AIC, BIC, and tests for nested models

Information criterion (general form)
\[ \color{#0B7B6B}{\text{IC}} = -2\ln\color{#C2410C}{\hat{L}} + \color{#6D28D9}{a} \times \color{#1D4ED8}{s} \]
IC information criterion maximised likelihood a penalty per parameter s number of parameters

Where \(s\) is the number of parameters and \(a\) is the penalty constant. For AIC, \(a = 2\) (Akaike, 1974). For BIC, \(a = \ln(n)\) (Schwarz, 1978). Smaller IC indicates a better model.

BIC differences: 0–2 = weak evidence; 2–6 = positive; 6–10 = strong; ≥10 = very strong.

Additional criteria

Adjusted R² and Mallow's Cₚ

Adjusted R-squared
\[ \color{#0B7B6B}{R^2_{\text{adj}}} = 1 - \frac{(\color{#C2410C}{n}-1)}{(\color{#C2410C}{n}-\color{#1D4ED8}{k}-1)}(1 - \color{#6D28D9}{R^2}) \]
R²₃ₐ₌ adjusted for predictors n sample size k number of predictors unadjusted R-squared

Where \(k\) is the number of predictors. Adjusted R² penalises complexity; maximise it. Mallow's Cₚ is a special case of AIC; minimise it.

Selection strategy

Backward, forward, and the dangers of stepwise

Backward elimination

Start with all predictors; remove one at a time. Each variable is evaluated in context. Preferred by Dohoo, Martin & Stryhn.

Avoid pure stepwise

Data-driven search overfits, produces optimistic standard errors, and yields models that fail to replicate (Babyak, 2004).

Combine any automated strategy with a protected list: primary predictors and known confounders are never removed by the algorithm.

Introduction and Overview

Earlier sections settled which predictors enter the model and how each one is shaped. This section closes the lesson with the most consequential remaining design choices: which interaction terms (if any) to include, how to think about moderation as a substantive question, and which selection criterion to use when several plausible models compete.

Learning Objectives

  • Identify interaction terms worth testing using subject-matter knowledge before searching the data.
  • Distinguish statistical interaction from substantive moderation and explain why the latter requires a substantive story rather than only a p-value.
  • Compare model-selection criteria (adjusted R2, AIC, BIC, cross-validation) and explain what each rewards.
  • Specify a model-building strategy (backward, forward, all-subsets, or theory-driven) and defend the choice.
  • Recognise the dangers of data-driven selection (overfitting, optimistic standard errors) and how to mitigate them (Babyak, 2004).

Identifying Interaction Terms

It is important to consider including interaction terms when specifying the maximum model. There are five general strategies for creating and evaluating 2-way interactions:

Strategy 1: Evaluate All Possible 2-Way Interactions

This is feasible only when the total number of predictors is small (e.g., ≤ 8). You create and test every possible pair of interaction terms.

Strategy 2: Interactions Among Significant Main Effects

After building the final main-effects model, create interactions among all predictors that are statistically significant. This reduces the number of interactions to evaluate but may miss interactions with non-significant main effects.

Strategy 3: Interactions Among Unconditionally Associated Predictors

Create interactions among all predictors that have a significant unconditional association with the outcome. This casts a wider net than Strategy 2.

Strategy 4: Theory-Driven Interactions

Only create interactions among pairs of variables you suspect (based on evidence from the literature or biological reasoning) might interact. This usually focuses on interactions involving the primary predictor(s) of interest and important confounders.

Strategy 5: Exposure-Only Interactions

Only create interactions that involve the exposure variable (primary predictor of interest). This is the most conservative approach but may miss important interactions among covariates.

⚠ Important Rules for Interactions

If an interaction term is included in the model, the main effects that make it up must also be included. Evaluating many interactions increases the risk of identifying spurious associations, so a Bonferroni adjustment or similar correction may be warranted. Three-way interactions are usually very difficult to interpret and should be included only if there is strong a priori reason.

Moderation: Interactions With a Substantive Story

In the regression literature, an interaction term is often called a moderation when it captures a substantive claim that the effect of one variable depends on another. A moderator W changes the slope of X → Y. Mathematically it is identical to an interaction (Y ~ X * W); the difference is conceptual.

Mediation vs. moderation, one more time

In an earlier section we used a DAG to set up mediation (X → M → Y, where M is on the causal pathway). Moderation is structurally different: W does not sit between X and Y, it changes the strength of the X → Y arrow. Mediation answers through what?; moderation answers for whom, or under what conditions?

R Activity: detect and visualise moderation in R

Using the built-in birthwt dataset (MASS package), we ask: does maternal age modify the effect of smoking on birth weight? If yes, smoking matters more (or less) for younger versus older mothers, a question about for-whom, not through-what.

# install.packages(c("MASS", "ggplot2", "interactions"))
library(MASS);  library(ggplot2);  library(interactions)
data("birthwt", package = "MASS")
bw <- birthwt
bw$smoke <- factor(bw$smoke, levels = c(0, 1),
                   labels = c("non-smoker", "smoker"))

# 1. Main-effects model (no moderation)
m_main <- lm(bwt ~ smoke + age, data = bw)

# 2. Moderation model: smoke * age
m_mod  <- lm(bwt ~ smoke * age, data = bw)

# 3. Is the moderation needed? Compare nested models with a likelihood-ratio
#    test (here, the partial F-test from anova() because models are linear).
anova(m_main, m_mod)

summary(m_mod)

# 4. Plot the moderation: smoking slopes at low / mean / high age
interact_plot(m_mod, pred = age, modx = smoke,
              interval = TRUE) +
  labs(y = "Birth weight (g)",
       title = "Effect of maternal age on birth weight, by smoking status")

# 5. Simple-slopes / Johnson-Neyman: across the range of maternal age,
#    where is the effect of smoking on birth weight distinguishable from zero?
sim_slopes(m_mod, pred = smoke, modx = age, johnson_neyman = TRUE)
Console output (truncated)
Analysis of Variance Table Model 1: bwt ~ smoke + age Model 2: bwt ~ smoke * age Res.Df RSS Df Sum of Sq F Pr(>F) 1 186 95672288 2 185 93062605 1 2609683 5.19 0.0239 * Coefficients (m_mod): Estimate Std. Error t value Pr(>|t|) (Intercept) 2406.1 292.2 8.23 <0.001 smokesmoker 798.2 484.3 1.65 0.101 age 27.7 12.1 2.28 0.024 smokesmoker:age -46.6 20.4 -2.28 0.024

Reading the moderation. The interaction term smokesmoker:age is negative and significant: as maternal age rises, smoking is linked to a larger drop in birth weight, so the smoker-versus-non-smoker deficit grows rather than shrinks with age. interact_plot() shows this as two non-parallel birth-weight-versus-age lines, one per smoking group; sim_slopes() with pred = smoke reports the estimated smoking effect at chosen maternal ages, each with a confidence interval. Activity: change the moderator from age to lwt (mother’s weight at last menstrual period). Does the effect of smoking on birth weight depend on maternal weight? Defend your answer with both the partial F-test and the plot.

R Reflect on what you just ran

Use the questions below to interpret the output you produced. Look at your console / plot before answering.

1. From anova(m_main, m_mod), what is the F statistic and p-value for adding the smoke:age interaction? Does adding the interaction significantly improve fit, and what does that tell you about whether age moderates the smoking-birthweight relationship?

Model answeranova(m_main, m_mod) gives F = 5.19 on 1 and 185 degrees of freedom, p = 0.024. Because p is below 0.05, adding the smoke:age interaction significantly improves fit. That is evidence of effect modification: the smoking effect on birth weight depends on maternal age. Retaining the interaction is supported by both the significant test and the substantive plausibility that smoking-related risk differs across maternal age.

2. In summary(m_mod), what is the smokesmoker:age coefficient and its sign? In one plain-English sentence, describe how the smoking-vs-non-smoking gap in birthweight changes as maternal age increases.

Model answerThe smokesmoker:age coefficient in m_mod is about −46.6 g per additional year of maternal age (p = 0.024). The non-smoker age slope is about +27.7 g/year, so the smoker slope is roughly 27.7 − 46.6 ≈ −19 g/year. Plain English: smoking's harm to birth weight is more pronounced in older mothers than in younger mothers, so the smoker-versus-non-smoker deficit grows as maternal age increases.

3. From sim_slopes(..., johnson_neyman = TRUE), identify the range of maternal age over which the effect of smoking on birthweight is statistically significant. Outside that region, what would you conclude about smoking's effect for that subgroup?

Model answerWith sim_slopes(pred = smoke, modx = age, johnson_neyman = TRUE), the Johnson-Neyman boundary falls near age 22: the effect of smoking on birth weight is statistically significant for mothers older than about 22 and is not distinguishable from zero below that. For younger mothers we cannot confirm a smoking effect in these data, but we also cannot rule one out; the boundary reflects statistical power (confidence intervals widen where smokers are sparse), not a biological threshold.
Saved.

Building the Model: Selection Criteria

Once the maximum model has been specified, you need to decide how to determine which predictors to retain. Both non-statistical and statistical criteria should be considered.

Non-Statistical Considerations

Variables should be retained in the model if they:

  • Are a primary predictor of interest
  • Are thought a priori to be confounders for the primary predictor
  • Show evidence of being a confounder (their removal causes a substantial change in the coefficient of interest)
  • Are a component of an interaction term included in the model

Statistical Criteria for Nested Models

Models where one model’s predictors are a subset of another’s are called nested models. Tests for nested models include:

  • Partial F-test (for linear regression)
  • Wald test (most commonly used; can be unreliable if P-values are near 0.05 or SEs appear suspect)
  • Likelihood-ratio test (LRT) (has the best statistical properties but requires fitting both models)

For categorical variables with multiple indicator terms, evaluate the overall significance of all indicators together, not individual terms.

In plain terms, each of these tests asks the same question: do the extra terms in the larger model explain enough additional variation to be worth the degrees of freedom they cost? A small p-value says yes.

Information Criteria (AIC & BIC)

For non-nested models, information criteria are used. The general formula is:

Information criterion (Eq 15.1)
\[ \color{#0B7B6B}{\text{IC}} = -2\ln\color{#C2410C}{\hat{L}} + \color{#6D28D9}{a} \times \color{#1D4ED8}{s} \]
An information criterion trades off model fit (via the maximised likelihood) against complexity: a penalty per parameter times the number of parameters. Lower is better.

Where s is the number of parameters, lnL is the log-likelihood, and a is a penalty constant. For AIC, a = 2 (Akaike, 1974). For BIC, a = ln(n) (Schwarz, 1978). Smaller values indicate a better model. BIC tends to favour more parsimonious models.

Reading the numbers. An AIC or BIC value means nothing on its own; a single value such as 1,240 is neither good nor bad. Only the difference between models carries information, and the comparison is valid only when the models are fit to the same outcome, measured the same way, on the same set of observations. That last condition catches beginners: you cannot compare the AIC of a model for Y against one for log(Y), and quietly dropping rows with missing values changes the sample, which makes the criteria incomparable.

Guidelines for interpreting BIC differences between models:

  • 0–<2: Weak evidence
  • 2–<6: Positive evidence
  • 6–<10: Strong evidence
  • ≥10: Very strong evidence

Adjusted R² & Mallow’s Cp

Adjusted R² maximises the variance explained while penalising unnecessary complexity. The model that maximises adjusted R² is preferred.

Mallow’s C_p (Eq 15.2)
\[ \color{#0B7B6B}{C_p} = \frac{\sum (\color{#C2410C}{Y} - \color{#6D28D9}{\hat{Y}})^2}{\color{#1D4ED8}{\sigma^2}} - \color{#BE185D}{n} + 2\color{#047857}{k} \]
Mallow’s Cp compares the observed and predicted values, scaled by the error variance, then adjusts for the sample size and the number of parameters. Values near k indicate a well-fitting subset.

Where k is the number of predictors in the candidate model, σ² is the MSE from the full model, and n is the sample size. Mallow’s Cp is a special case of the AIC. The model with the lowest Cp is generally considered the best.

Specifying the Selection Strategy

Once criteria are established, there are several strategies for selecting which variables to include in the final model.

All Possible SubsetsClick to explore
Forward SelectionClick to explore
Backward EliminationClick to explore

Best Practice Summary

Backward elimination is generally preferred over forward selection because each predictor is evaluated in the context of all others. However, the most important point is to combine statistical procedures with subject matter knowledge: retain known confounders and primary predictors regardless of statistical criteria, and always build a causal model first (Heinze, Wallisch, & Dunkler, 2018).

Knowledge check: this section

1. If an interaction term between variables A and B is included in a regression model, which of the following must also be true?

If an interaction term (A × B) is included in the model, the main effects for both A and B must also be included. This is required for the interaction term to be properly interpretable and is a standard rule in regression modelling.

2. What is the key difference between AIC and BIC?

Both AIC and BIC use the formula IC = −2 lnL + a × s, but the penalty constant a differs. AIC uses a = 2 while BIC uses a = ln(n), which is larger for any n > 7. BIC therefore imposes a heavier penalty for adding parameters, tending to favour simpler models.

3. Why is backward elimination generally preferred over forward selection?

Backward elimination starts with all predictors in the model, so each variable is evaluated in the presence of all others. This is better at identifying important predictors whose individual effect may be masked or suppressed by confounding. Forward selection examines each predictor in isolation first, potentially missing such effects.

✎ Reflection

Reflect on the tension between statistical model selection (AIC, BIC, stepwise methods) and subject matter knowledge. Why might a model selected purely by statistical criteria fail to answer your research question?

Model answerPure statistical model selection (stepwise, lasso (Tibshirani, 1996), AIC/BIC) optimises a goodness-of-fit criterion that does not encode the causal question. The model that minimises AIC may include a mediator (because it predicts the outcome well) or exclude a confounder (because it doesn't add much to the fit), both of which produce biased causal estimates. Stepwise procedures are especially problematic: they over-fit to the sample, produce non-reproducible models, and yield p-values and CIs that are demonstrably wrong (the model itself depends on the data being analysed). Subject-matter knowledge encoded in a pre-specified DAG produces an adjustment set that statistically may not be "the best" by AIC but is the right one for the causal question. The right role for AIC/BIC is in comparing pre-specified models with the same identification strategy, not in choosing which variables to include.
✓ Reflection saved!
Complete the quiz and reflection to continue.
Final Assessment

Lesson 3: Comprehensive Assessment

⏱ Estimated time: 30 minutes

Bringing It All Together

This module took the dataset you cleaned in an earlier lesson and built the two regression engines that the rest of the course runs on. The first part introduced the simple and multivariable linear model and made clear how each coefficient should be read; used the ANOVA decomposition, t-tests, and confidence intervals to ask whether the model and each coefficient are doing useful work; dealt with the messiness of real predictors (scaling, dummy coding, hierarchical indicators, and VIF for the collinearity that quietly destabilises coefficients); and closed by adding interactions and giving the fitted model a defensible causal reading through a DAG.

The second part took the binary outcome, the most common outcome in epidemiology, and showed why ordinary linear regression breaks for dichotomous data and how the logit transformation rescues it. From there it moved through coefficient interpretation as adjusted odds ratios, the likelihood-ratio and Wald tests, the assessment of confounding and interaction on the logit scale, and the evaluation toolkit of residuals, Hosmer–Lemeshow, ROC curves, calibration, pseudo-R², and overdispersion, before placing logistic regression inside the wider GLM family and flagging the exact and conditional variants for sparse and matched data.

The third part stepped back to the question that both engines raise: given a clean dataset and a working regression, which predictors belong in the final model, and in what form? It distinguished prediction goals from causal-explanation goals, confronted too many candidate predictors and too many missing values, asked how to model curvature with smoothers, categorisation, polynomials, and splines, and closed with interactions, moderation, and the selection criteria (adjusted R², AIC, BIC, cross-validation) that adjudicate between candidate models. The recurring lesson is that model building is a chain of small, defensible decisions, each made before looking at the next p-value. The final assessment asks you to move fluently between the two engines, to interpret coefficients on the scale each model uses, to choose appropriate diagnostics, and to justify what enters the model and why. A later lesson extends the same maximum-likelihood machinery to ordinal, multinomial, count, and rate outcomes.

Key Takeaways from this lesson

  • Linear regression models a continuous outcome as a weighted sum of predictors plus normally distributed error; the ANOVA decomposition, F-tests, and t-tests assess overall fit and individual coefficients.
  • Categorical predictors must be entered as indicator variables, multicollinearity inflates standard errors without changing predictions (check VIFs), and an interaction term means the effect of one predictor depends on another.
  • A regression earns a causal interpretation only when the DAG, adjustment set, and assumptions are stated explicitly, not by default.
  • Logistic regression models the log odds of a binary outcome as a linear function of predictors; an exponentiated coefficient is an adjusted odds ratio, and a coefficient on a continuous predictor scales multiplicatively with the size of the change.
  • The likelihood ratio test is generally preferred to the Wald test, and goodness-of-fit needs both calibration (Hosmer–Lemeshow, calibration plots) and discrimination (ROC/AUC).
  • Linear and logistic regression are members of the GLM family; when data are sparse, severely unbalanced, or matched, switch to exact or conditional logistic regression rather than forcing standard ML to converge.
  • Model-building strategy depends on the goal: prediction tolerates noisy predictors for accuracy; causal explanation retains confounders and excludes mediators regardless of significance, and the predictor set should be driven by subject-matter knowledge and causal structure rather than stepwise procedures.
  • Missing-data handling must match the missingness mechanism, and continuous predictors deserve a functional-form check (categorisation, polynomials, and splines solve different problems).
  • Interaction terms should be specified before looking at the data, and model-selection criteria (adjusted R², AIC, BIC, cross-validation) reward different things; pick the criterion that matches the analytic goal and report it transparently.

This final assessment covers all material from the module. You must answer all 15 questions correctly (100%) and complete the final reflection to finish the lesson.

Reflection

A cohort study has measured systolic blood pressure (continuous) and a clinical diagnosis of hypertension (yes/no) in 2,400 adults, along with two dozen candidate predictors that include an exposure of primary interest, several plausible confounders, a likely mediator, and some variables with substantial missingness. Reflecting on all three parts of this module, walk through how you would build, fit, check, and report a model for each outcome: how the causal diagram and the goal of the analysis decide what enters the model, how you would handle the predictor set, functional form, missing values, and interaction, how the linear and logistic coefficients would be interpreted on their respective scales, which diagnostics you would run for each engine, and how you would present the two sets of results side by side.

Model answerStart with the question and the DAG: the goal is the causal effect of the exposure on blood pressure and on hypertension, so the adjustment set is the minimal sufficient set of confounders read off the DAG, the mediator is excluded (adjusting for it would remove part of the total effect), and this is written down before any model is fitted. Reduce the candidate predictors by substantive screening, collinearity checks (VIF) and, where several items measure one construct, an index with acceptable Cronbach's alpha; characterise the missingness mechanism and use multiple imputation under MAR rather than defaulting to complete-case analysis; check the functional form of continuous predictors with scatterplots and smoothers and use a spline or fractional polynomial where the relationship is curved; pre-specify the one or two interactions with a substantive moderation story. For blood pressure fit a multivariable linear model: coefficients are adjusted differences in mean mmHg per unit of the predictor, categorical predictors enter as indicators against a stated reference category, and the diagnostics are residuals versus fitted values (linearity and homoscedasticity), a Q-Q plot (normality), Cook's distance (influence) and VIFs. For the hypertension diagnosis fit a logistic model with the same adjustment set: exponentiated coefficients are adjusted odds ratios, a continuous predictor's odds ratio scales as OR to the power of the change, inference uses likelihood-ratio tests in preference to Wald tests, and evaluation needs both calibration (Hosmer–Lemeshow and a calibration plot) and discrimination (ROC/AUC), with a check for overdispersion and, if events are sparse, exact logistic regression. Compare candidate specifications with AIC or BIC and cross-validation rather than stepwise selection, run sensitivity analyses (alternative functional forms, complete-case versus imputed data, alternative adjustment sets under competing DAGs), and report both models in one table with the adjustment set, the scale of each effect (mean difference versus odds ratio), confidence intervals, the diagnostics performed, and the pre-registered versus exploratory analyses clearly separated.

Minimum 20 characters required.

✓ Reflection saved

Final Knowledge Assessment

Final assessment: the 15 questions

1. In a multivariable model, β1 represents the effect of X1 on Y:

A key feature of multivariable regression is that each coefficient estimates the effect of its predictor while holding all other variables constant, thereby controlling for their effects.

2. Why should we use adjusted R² rather than R² when comparing models?

R² always increases with more predictors. Adjusted R² = 1 − (MSE/MST) accounts for the number of predictors and will decline if added variables contribute little additional information.

3. To code a nominal variable with 5 categories for regression, you would create:

For a nominal variable with j levels, j − 1 indicator variables are needed. The omitted level becomes the referent category. With 5 categories, 4 indicators are required.

4. A VIF of 1.0 for a predictor indicates that:

VIF = 1/(1 − R²x). If R²x = 0 (no correlation with other predictors), VIF = 1.0, indicating no collinearity. The variance of β is not inflated at all.

5. Including an intervening variable in a causal regression model will:

If a variable lies on the causal pathway between exposure and outcome (an intervening/mediator variable), including it in the model removes the portion of the exposure effect that operates through that pathway, yielding only the direct effect rather than the total effect.

6. Why can’t linear regression be used for dichotomous outcomes?

Linear regression is inappropriate for binary outcomes because: (1) errors follow a binomial rather than normal distribution, (2) the variance of errors depends on the predicted probability (heteroscedasticity), and (3) predicted values can fall outside the meaningful 0–1 range.

7. In logistic regression, OR = eβ1 represents:

Exponentiating the coefficient β1 gives the odds ratio associated with a 1-unit increase in X1, holding all other predictors constant. For dichotomous predictors, this is the OR comparing the two groups.

8. For a continuous predictor, the OR for a change from x1 to x2 is:

For a continuous predictor, the OR for a change of (x2 − x1) units is eβ(x2 − x1), which equals (eβ)(x2 − x1) = OR(x2 − x1). This allows you to compute the OR for any meaningful increment rather than only a 1-unit change.

9. An ROC curve that closely follows the 45° diagonal indicates:

The 45-degree diagonal on an ROC curve represents random classification (AUC = 0.5). A curve that closely follows this diagonal means the model cannot discriminate between positive and negative outcomes any better than chance.

10. Conditional logistic regression is used for:

Conditional logistic regression is designed for matched case-control studies. It uses a conditional likelihood that eliminates stratum-specific parameters, avoiding the bias that can occur when unconditional logistic regression is used with many matched strata.

11. What is the purpose of drawing a causal diagram before model building?

A causal diagram maps potential causal relationships among predictors and the outcome. It helps distinguish confounders (which should be retained) from intervening variables (which should generally be excluded when estimating total effects).

12. What does MNAR mean in the context of missing data?

MNAR (Missing Not at Random) means the probability of a value being missing depends on the unobserved value itself. For example, sicker patients may be less likely to attend follow-up, so the missing health data would be systematically different from the observed data.

13. What are knot points in the context of splines?

In spline models, knot points are the values of the predictor where the slope of the fitted line is allowed to change. Between knots, the relationship is assumed to be linear (for linear splines) or follow a polynomial curve (for cubic splines).

14. Which of the following is NOT a non-statistical reason to retain a variable in the model?

Having P < 0.05 in univariable analysis is a statistical criterion, not a non-statistical one. Non-statistical reasons include being a primary predictor, a suspected confounder, or part of an interaction term already in the model.

15. Why is backward elimination generally preferred over forward selection?

Backward elimination starts with all predictors, so each one is evaluated while controlling for all others. This is better at identifying important predictors whose individual effect might be suppressed or masked by confounding when examined in isolation (as occurs in forward selection).

✦ Before submitting: pass every section knowledge check (100%) and complete every reflection.

This lesson Complete!

A later lesson, Generalized Linear Models, extends the maximum-likelihood machinery you built here to outcomes with more than two categories and to counts and rates. The link function changes, but the model-building discipline carries over directly.

Congratulations! You have successfully completed this lesson: Linear & Logistic Regression. Your responses have been downloaded automatically.