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.
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.
Introduction & Regression Analysis
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.
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.
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.
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.
✏ 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).
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.
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.
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.
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.
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.
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).
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.
summary(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?
VIF(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.1. What type of outcome variable is linear regression most suitable for?
2. In the equation Y = β0 + β1X1 + ε, what does β1 represent?
3. What is the key advantage of a multivariable regression model over a simple regression model?
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?
Hypothesis Testing & Effect Estimation
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).
| Source | Sums of Squares | df | Mean Square | F-test |
|---|---|---|---|---|
| Model (regression) | SSM = Σ(Ŷi − Ȳ)2 | dfM = k | MSM = SSM/dfM | MSM/MSE |
| Error (residual) | SSE = Σ(Yi − Ŷi)2 | dfE = n−(k+1) | MSE = SSE/dfE | |
| Total | SST = Σ(Yi − Ȳ)2 | dfT = n−1 | MST = 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.
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.
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² (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.
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.
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).
1. What does the F-test in the ANOVA table assess?
2. What does R² (the coefficient of determination) measure?
3. Why is adjusted R² preferred over R² when comparing models with different numbers of predictors?
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?
Nature of X-Variables & 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.
| Variable | Indicator Coding | Hierarchical Coding |
|---|---|---|
| meduc_c4=2 (high school diploma) | 20.046 | 20.046 |
| meduc_c4=3 (some college) | 53.270 | 33.224 |
| meduc_c4=4 (university degree) | 80.599 | 27.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.
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.
1. For a nominal variable with 4 categories, how many indicator (dummy) variables are needed?
2. What does a VIF value greater than 10 suggest?
3. What is the primary purpose of centring a continuous variable before adding it to a regression model?
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?
Interaction & Causal Interpretation
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.
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.
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 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.
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.
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.
1. What does a significant interaction term (β3) in a regression model indicate?
2. When estimating the total causal effect of an exposure, what should you do with intervening variables?
3. What tool is recommended before building a multivariable model to help distinguish confounders from intervening variables?
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?
Introduction & The Logistic Model
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:
- 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.
- Heteroscedasticity: The variance of the residuals depends on the predicted probability, so the assumption of constant variance is violated.
- 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.
The Logistic Model
The logistic regression model expresses the log odds of the outcome as a linear combination of predictors:
The inverse logit (or logistic function) converts back to the probability scale:
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:
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^−η)
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.
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.
1. What does the logit function transform?
2. In a logistic regression, how is the odds ratio for a dichotomous predictor computed?
3. Why is maximum likelihood estimation (MLE) used instead of least squares for logistic regression?
✎ 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?
Interpreting Coefficients & Assessing Confounding
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:
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
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.
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:
For example, if βage = 0.04, the OR per 10-year increase in age is e0.04 × 10 = e0.4 = 1.49.
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.
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.
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?
exp(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.
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?
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).
1. The likelihood ratio test (LRT) compares models by:
2. For a continuous predictor, what does the odds ratio represent?
3. When assessing confounding in logistic regression, you should:
✎ 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?
Evaluating Logistic Regression Models
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
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).
| Concept | Definition | Also Known As |
|---|---|---|
| Sensitivity | Proportion of true positives correctly identified by the model | True positive rate |
| Specificity | Proportion of true negatives correctly identified by the model | True negative rate |
| Cutpoint | The predicted probability threshold above which subjects are classified as positive | Classification 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 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 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).
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.
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.
1. What does the Hosmer-Lemeshow test evaluate?
2. What does an ROC curve AUC of 0.5 indicate?
3. The minimum sample size rule for logistic regression suggests:
✎ 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?
GLMs, Exact & Conditional Logistic Regression
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 Type | Distribution | Canonical Link | Example |
|---|---|---|---|
| Continuous | Gaussian (Normal) | Identity | Linear regression |
| Binary | Binomial | Logit | Logistic regression |
| Count | Poisson | Log | Poisson regression |
| Count (overdispersed) | Negative Binomial | Log | NB 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.
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 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.
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)
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.
1. In the GLM framework, what are the two key components that must be specified?
2. When is exact logistic regression preferred over standard logistic regression?
3. In conditional logistic regression for matched data, why is the intercept not estimated?
✎ 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?
Introduction & Steps in Model Building
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.
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.
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.
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.
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.
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.
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.
1. When the goal of a regression model is to understand biological relationships, which of the following is true?
2. What is the first step in building a regression model?
3. In a study of cigarette smoking’s effect on birth weight, why should gestation length generally NOT be included in the model?
✎ 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?
Reducing Predictors & Missing Values
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
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.
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 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 (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.
1. What does Cronbach’s alpha measure?
2. Under which missing data mechanism is complete case analysis most likely to produce biased results?
3. Why is multiple imputation generally preferred over single imputation?
✎ 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?
Effects of Continuous Predictors
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.
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.
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:
- Categorisation involves the loss of information
- It is unlikely that biological processes have a step-function relationship (i.e., sudden changes at specific cutpoints)
- 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.
⚠ 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.
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).
| Approach | Influence | Strengths | Limitations |
|---|---|---|---|
| Smoothed lines | Local | Flexible; reveals non-linearity | Cannot be used in model itself; issues at extremes |
| Categorisation | N/A | Avoids linearity assumption | Loses information; arbitrary cutpoints |
| Polynomials | Global | Simple to implement; formal tests | May over-fit at extremes; collinearity |
| Fractional polynomials | Global | Very flexible with few terms | Coefficients not directly interpretable |
| Splines | Local | Flexible; smooth transitions | Sudden shifts at knots (linear splines) |
1. Why is categorising a continuous predictor generally not advisable?
2. What is a key difference between smoothed lines and polynomial models?
3. Why should you centre a continuous variable before adding its squared term to a regression model?
✎ 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?
Interactions & Building the Model
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:
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.
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.
Create interactions among all predictors that have a significant unconditional association with the outcome. This casts a wider net than Strategy 2.
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.
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?
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)
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?
anova(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.
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?
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.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:
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.
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.
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).
1. If an interaction term between variables A and B is included in a regression model, which of the following must also be true?
2. What is the key difference between AIC and BIC?
3. Why is backward elimination generally preferred over forward selection?
✎ 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?
Lesson 3: Comprehensive Assessment
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.
Minimum 20 characters required.
Final Knowledge Assessment
1. In a multivariable model, β1 represents the effect of X1 on Y:
2. Why should we use adjusted R² rather than R² when comparing models?
3. To code a nominal variable with 5 categories for regression, you would create:
4. A VIF of 1.0 for a predictor indicates that:
5. Including an intervening variable in a causal regression model will:
6. Why can’t linear regression be used for dichotomous outcomes?
7. In logistic regression, OR = eβ1 represents:
8. For a continuous predictor, the OR for a change from x1 to x2 is:
9. An ROC curve that closely follows the 45° diagonal indicates:
10. Conditional logistic regression is used for:
11. What is the purpose of drawing a causal diagram before model building?
12. What does MNAR mean in the context of missing data?
13. What are knot points in the context of splines?
14. Which of the following is NOT a non-statistical reason to retain a variable in the model?
15. Why is backward elimination generally preferred over forward selection?
✦ Before submitting: pass every section knowledge check (100%) and complete every reflection.