Modelling Dependent Data
Exploratory Data Analysis For Epidemiology
Learning objectives for this lesson:
- Recognize and describe clustered (hierarchical) and repeated-measures data structures in epidemiology, and explain why observations within clusters or subjects are correlated
- Calculate and interpret the intraclass correlation coefficient (ICC), the design effect (deff), and the effective sample size, and evaluate the consequences of ignoring clustering for standard errors, inference, and Type I error
- Describe the methods for dealing with clustering (fixed effects, correction factors, robust variance estimators, survey methods, GEE, and mixed models) and choose among them according to the number of clusters and whether the question is marginal or conditional
- Write and interpret the linear mixed model with random intercepts and random slopes, decompose variance into between-group and within-group components, and interpret random slopes models as hierarchical models
- Explain contextual effects and group-mean centering, describe ML and REML estimation and their properties, and conduct inference for both fixed and random effects
- Use BLUPs, shrinkage, residuals at each level of the hierarchy, and model diagnostics to validate a linear mixed model
- Write and interpret generalised linear mixed models (GLMMs) for binary, count, ordinal, and multinomial outcomes, and distinguish subject-specific (SS) from population-averaged (PA) interpretations
- Calculate the median odds ratio (MOR) and the latent-variable ICC for binary outcomes
- Explain the estimation challenges of GLMMs (ML, quasi-likelihood, Laplace approximation, adaptive quadrature, and Bayesian estimation) and evaluate when each method is appropriate
- Explore repeated-measures data with descriptive and graphical tools, apply simple univariate approaches, and explain where classical methods and random-intercept models break down
- Choose among correlation structures (compound symmetry, AR(1), ARMA(1,1), Toeplitz, unstructured) and fit linear mixed models with appropriate correlation structures and trend models with random slopes for time
- Extend the framework to discrete repeated measures through GLMMs and transition models, and use GEE procedures to analyse clustered and repeated-measures data
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 & Types of Clustered Data
Introduction and Overview
Earlier lessons systematically built up the regression toolkit for different outcome types (continuous, binary, ordered, multi-category, count, and time-to-event), but every one of those models rested on a single shared assumption: observations are independent. Real epidemiologic data almost never satisfy that assumption. Patients are nested within clinics, students within classrooms, repeated measurements within people, and households within neighbourhoods. This lesson opens the final arc of the course by taking that assumption head-on.
The four content sections build the case in stages. This section defines clustered data and catalogues the common ways it arises in public health research. A later section shows analytically why clustering breaks standard inference: standard errors collapse, Type I error rates inflate, and conclusions drift. A later section uses simulation to make the consequences tangible: you will see what happens to confidence intervals and p-values when you ignore clustering at different intra-cluster correlations. A later section previews the family of methods designed to handle clustering (mixed effects, GEE, robust/sandwich variances, and design-based survey adjustments), setting up the deeper treatment in later lessons.
Learning Objectives
- Define clustered (hierarchical) data and contrast it with the independent-observations assumption of standard regression.
- Identify common sources of clustering in public-health research, including environmental, spatial, repeated-measures, and design-induced grouping.
- Explain how within-cluster similarity arises from shared exposures, contexts, or stable subject-level traits.
- Distinguish predictor clustering from outcome clustering and recognise both in study descriptions.
What Is Clustered Data?
In many epidemiologic studies, observations are not independent. Instead, they are grouped within higher-level units, and these groups are called clusters. Clustered (or hierarchical) data arises whenever the study design or the natural structure of the population creates groupings such that observations within the same group tend to be more similar to each other than to observations in other groups (Galbraith, Daniel, & Vissel, 2010; Killip, Mahfoud, & Pearce, 2004).
Why Clustering Matters
Standard statistical methods assume observations are independent. When data are clustered, this assumption is violated: observations within the same cluster share common influences (e.g., the same hospital, the same household, the same geographic region). Ignoring clustering can lead to underestimated standard errors, inflated Type I error rates, and potentially biased point estimates (Donner & Klar, 2004).
Types of Clustered Data
Clustering arises from many different sources. Understanding the type of clustering present in your data is the first step toward choosing an appropriate analytical strategy.
In veterinary epidemiology, animals within the same herd share management practices, nutrition, housing, and disease exposure. Similarly, patients within the same hospital share institutional protocols, staffing levels, and local disease ecology. These shared exposures create within-cluster correlation: outcomes for subjects in the same cluster are more alike than for subjects in different clusters.
People living near each other are often exposed to similar environmental factors: air pollution, water quality, neighbourhood safety, socioeconomic deprivation, and access to healthcare services. This means that health outcomes for individuals in the same geographic area are correlated. Studies that sample from defined geographic areas (e.g., census tracts, postal codes) must account for this spatial clustering.
When the same subjects are measured multiple times (e.g., before and after treatment, or at regular intervals in a cohort study), each subject forms a cluster. The repeated observations within a subject are correlated because stable individual characteristics (genetics, baseline health, behaviour) influence all measurements. The correlation structure depends on the timing and spacing of measurements.
Many real-world data structures have multiple levels. For example, students are nested within classrooms, classrooms within schools, and schools within districts. Each level contributes its own source of variation. In epidemiology, patients may be nested within physician practices, practices within health regions, and regions within provinces. Split-plot designs from experimental settings also create hierarchical structures where treatments are applied at different levels of the hierarchy.
Cross-classified structures arise when subjects belong to multiple grouping factors that do not nest within each other. For example, students may be classified by both school and neighbourhood, and students from the same neighbourhood may attend different schools, and students from the same school may live in different neighbourhoods. Split-plot designs, common in agricultural experiments, have some factors applied at the whole-plot (cluster) level and others at the subplot (individual) level.
Sources of Variation & Predictor Clustering
In clustered data, the total variation in the outcome can be decomposed into between-cluster variation (differences between groups) and within-cluster variation (differences among individuals within the same group). The relative magnitude of these two sources of variation determines the strength of the clustering effect.
An important consideration is predictor clustering, which occurs when predictor variables also vary between clusters. If both the exposure and the outcome vary at the cluster level, group-level associations may differ from individual-level associations. This is the basis of the ecological fallacy: inferring individual-level relationships from aggregate (group-level) data.
1. Which is an example of clustered data?
2. What is cross-classified data?
3. Why does predictor clustering matter?
Reflection
Think of a research study in your field. What natural clustering structures might exist in the data? How might ignoring this clustering affect your conclusions?
Effects of Clustering on Statistical Analysis
Introduction and Overview
From recognising clustering to quantifying its damage. An earlier section catalogued where clustered structures come from. This section answers the natural follow-up question: so what? When observations within a cluster are even mildly correlated, the precision implied by a naive analysis, one that pretends every observation is independent, is far too optimistic. Here we develop the formal vocabulary (the intraclass correlation, the design effect, the effective sample size) that makes the size of that distortion measurable. These quantities reappear in every method we cover in a later section and in later lessons, so it is worth slowing down on the intuition.
Learning Objectives
- Explain why ignoring clustering produces standard errors that are too small and Type I error rates that are too large.
- Compute the intraclass correlation coefficient (ICC) from between- and within-cluster variance components.
- Calculate the design effect (deff) and effective sample size from the ICC and average cluster size.
- Translate a given ICC and cluster size into a quantitative statement about precision loss.
Impact on Standard Errors
The most important consequence of clustering is its effect on standard errors. When observations within clusters are positively correlated (as is almost always the case), treating them as independent leads to standard errors that are too small. This in turn produces test statistics that are too large, P-values that are too small, and confidence intervals that are too narrow, all of which inflate the Type I error rate.
Why correlated observations carry less information
Imagine interviewing five people from the same household about what they eat. Because they shop and cook together, the second through fifth answers mostly echo the first, so you learn far less than you would from five unrelated people. Observations within a cluster behave the same way: when they are correlated, each additional member adds only a fraction of the fresh information that a genuinely independent observation would. A naive analysis still counts every observation as fully informative, so it credits itself with more information than it actually has, which is why its standard errors come out too small.
Imagine a study of 1,000 patients in 20 hospitals (50 per hospital). If the ICC is 0.05, the design effect is 1 + (50 − 1)(0.05) = 3.45. The effective sample size is only 1,000/3.45 ≈ 290 rather than 1,000. A naive analysis treating all 1,000 observations as independent would dramatically overstate the precision of estimates.
The Intraclass Correlation Coefficient (ICC)
For continuous outcomes, the ICC (intraclass correlation coefficient) measures the proportion of total variance that is attributable to between-cluster differences. It quantifies the degree of similarity among observations within the same cluster, a quantity formalised by the intraclass correlation (Killip, Mahfoud, & Pearce, 2004).
Here, σ²g is the between-cluster variance and σ² is the within-cluster variance. An ICC of 0 means no clustering effect (all variance is within clusters), while an ICC of 1 means all variance is between clusters.
The dataset phaa_clinics.csv contains 30 primary-care clinics with 18-45 patients each (~960 patients total). The continuous outcome sbp is influenced by both patient-level covariates (age, smoker, bmi) and clinic-level covariates (clinic_size, clinic_urban). The full annotated script is in r-activities/HSCI_410_Lesson_9_Introduction_to_Clustered_Data.R.
library(lme4); library(performance); library(sandwich); library(lmtest)
clinics <- read.csv("phaa_clinics.csv", stringsAsFactors = FALSE)
clinics$clinic_id <- factor(clinics$clinic_id)
# 1. ICC from a one-way ANOVA
aov_fit <- aov(sbp ~ clinic_id, data = clinics)
ms <- summary(aov_fit)[[1]][, "Mean Sq"]
n_per <- mean(table(clinics$clinic_id))
icc_h <- (ms[1] - ms[2]) / (ms[1] + (n_per - 1) * ms[2])
icc_h
# 2. Same ICC, conveniently, from a null mixed model
m_null <- lmer(sbp ~ 1 + (1 | clinic_id), data = clinics)
icc(m_null)
# 3. Design effect
deff <- 1 + (n_per - 1) * icc_h; deff
nrow(clinics) / deff # effective sample size
# 4. Cluster-robust SEs as a quick fix for naive OLS
naive <- lm(sbp ~ age + smoker + bmi + clinic_urban, data = clinics)
coeftest(naive, vcov. = vcovCL, cluster = ~ clinic_id)
Reading the output. An ICC of about 0.08 to 0.10 means roughly 8 to 10 percent of total variation in SBP is between clinics. The design effect (here around 3.5 to 4 with average cluster size 32) tells you cluster sampling has inflated by roughly three to four times the variance you'd get under SRS. Cluster-robust SEs are the easiest fix when you can't refit the analysis as a mixed model.
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. Report your icc_h value (from the one-way ANOVA) and the ICC from icc(m_null). Are they the same (or very close)? In one sentence, what fraction of total variance in SBP lies between clinics?
icc_h from the one-way ANOVA and icc(m_null) from the random-intercept model return nearly identical values, because both estimate the same quantity: the ratio of between-cluster variance to total variance. For this clinic dataset the ICC lands in the neighbourhood of 0.08 to 0.10, so roughly 8 to 10 percent of total variance in SBP lies between clinics and the remaining 90 percent or so is within-clinic (between individuals). This is a moderate ICC, and not unusual for a physiological measure in a multi-clinic cohort.2. Compute and report the design effect deff and the effective sample size nrow(clinics) / deff. In one sentence, explain what the deff means in practical terms (e.g., "each observation carries the information of...").
deff = 1 + (m−1)*ICC. With an average cluster size near 32 (about 960 patients across 30 clinics) and an ICC near 0.09, deff = 1 + 31×0.09 ≈ 3.8. Effective sample size = nrow(clinics) / deff ≈ 960 / 3.8 ≈ 250. Practical meaning: each clinic-clustered observation carries the information of only about 0.26 of an independent observation, so the roughly 960 rows are worth only about 250 genuinely independent ones. The design effect quantifies how much statistical power is ‘wasted’ because nearby observations within a clinic share information.3. Compare the naive OLS SEs from summary(naive)$coef[, "Std. Error"] to the cluster-robust SEs from coeftest(naive, vcov. = vcovCL, cluster = ~ clinic_id). Which predictor sees the biggest SE inflation, and why does ignoring clustering produce SEs that are too small?
The Design Effect (deff)
The design effect (also called the variance inflation factor in the clustering context) quantifies how much the variance of an estimate is inflated due to clustering, compared to what it would be under simple random sampling (Campbell, Elbourne, & Altman, 2004).
Where m̄ is the average cluster size and ρ is the ICC. The practical meaning: if ICC = 0.05 and cluster size = 20, then deff = 1 + (20 − 1)(0.05) = 1.95, meaning the effective sample size is roughly halved.
🏘 Interactive: ICC, Design Effect & Type I Error Inflation
Generate a clustered dataset (e.g., students within schools, patients within hospitals) under the null hypothesis: the treatment has no real effect. Run many simulated studies and watch how often a naive (clustering-ignoring) test wrongly declares significance. The Type I error inflation is the cost of pretending clustered data is independent.
One simulated dataset
Each color = a cluster. Within-cluster similarity grows with ICC.
Type I error: naive vs. cluster-aware test
Effects on Continuous Outcomes
For continuous outcomes, the ICC directly measures the proportion of total variance due to between-cluster differences. The design effect formula deff = 1 + (m̄ − 1)ρ applies straightforwardly. The corrected standard error is obtained by multiplying the naive SE by √deff.
Example: With 20 clusters of 50 subjects each (n = 1,000), ICC = 0.05, the deff = 3.45. A naive SE of 0.50 would become 0.50 × √3.45 = 0.93, nearly double the naive estimate.
Effects on Discrete Outcomes
With binary or other discrete outcomes, the effects of clustering are analogous but more complex. Clustering affects the standard error estimation and can also influence point estimates. The design effect concept extends to discrete outcomes, but the ICC for binary data is defined differently and its estimation is more involved.
For binary outcomes, the variance of a proportion under clustering is inflated by a factor analogous to the deff. The practical consequence is the same: ignoring clustering leads to underestimated SEs and inflated Type I error.
| Analysis Approach | SE Estimate | 95% CI Width | P-value |
|---|---|---|---|
| Naive (ignoring clustering) | 0.50 | 1.96 | 0.001 |
| Cluster-adjusted (deff = 3.45) | 0.93 | 3.64 | 0.077 |
This table illustrates how accounting for clustering nearly doubles the standard error, widens the confidence interval, and can change a “significant” result to a non-significant one.
1. If the ICC is 0.10 and average cluster size is 21, what is the design effect?
2. What happens to Type I error rates when clustering is ignored?
3. The ICC represents:
Reflection
A study reports p = 0.03 for a treatment effect, but the data come from 10 hospitals with 50 patients each. If the ICC is 0.05, calculate the design effect and discuss whether the finding might still be significant after accounting for clustering.
Simulation Studies & Impact of Clustering
Introduction and Overview
From formulas to felt consequences. An earlier section gave us the mathematical machinery (ICCs, design effects, effective sample sizes) that explains why clustering inflates false-positive rates. This section translates those formulas into something visceral. Simulation studies generate data with a known clustering structure and then analyse it both correctly (accounting for clusters) and incorrectly (ignoring them), so we can measure the gap directly. The takeaway you should carry forward: even small ICCs can produce alarming Type I error inflation when cluster sizes are moderate or large, and that empirical fact is what motivates the methods previewed in a later section.
Learning Objectives
- Describe how simulation studies quantify the consequences of misspecified analyses under known data-generating processes.
- Predict the direction and approximate magnitude of Type I error inflation given an ICC and cluster size.
- Distinguish confounding by cluster from clustering of outcomes, and explain why each requires a different analytical response.
- Use simulation results to justify the choice of a clustered-data analysis method on practical as well as theoretical grounds.
Why Simulation Studies?
Simulation studies allow us to examine the practical consequences of ignoring clustering under controlled conditions. By generating data with known clustering structures and then analysing it both correctly and incorrectly, we can quantify the bias and Type I error inflation that results from ignoring the cluster structure (Galbraith, Daniel, & Vissel, 2010; Donner & Klar, 2004).
Warning: Ignoring Clustering Can Be Dangerous
Even moderate ICC values (e.g., 0.01–0.05) can lead to substantially inflated Type I error rates when cluster sizes are large. A study with ICC = 0.01 and 50 clusters of 50 subjects can have an actual Type I error rate of 10–15% instead of the nominal 5%. Researchers who ignore clustering risk reporting findings that appear statistically significant but are actually false positives.
Binary Outcome Simulations
Simulation studies with binary outcomes demonstrate that the consequences of ignoring clustering can be severe. Even when the ICC is small, the combination of within-cluster correlation and moderate-to-large cluster sizes can inflate the actual Type I error rate well beyond the nominal 5% level.
With ICC = 0.01 and 50 subjects per cluster, the design effect is deff = 1 + (50 − 1)(0.01) = 1.49. Although this seems modest, simulation studies show the actual Type I error rate can reach 10–15% depending on the number of clusters and the analysis method. The inflation occurs because the naive analysis assumes 50 independent observations per cluster when, in reality, the effective number is only about 34.
With ICC = 0.05 and 20 subjects per cluster, the design effect is deff = 1 + (20 − 1)(0.05) = 1.95. The effective sample size is nearly halved. Simulation studies show actual Type I error rates of 15–25% when the naive analysis is used. This means that one in four or five “significant” findings may be false positives.
With ICC = 0.10 and 30 subjects per cluster, the design effect is deff = 1 + (30 − 1)(0.10) = 3.90. The effective sample size is reduced to about one-quarter of the nominal size. Simulation studies demonstrate Type I error rates exceeding 30–40% when clustering is ignored. This level of inflation makes the naive analysis essentially unreliable.
Confounding by Cluster
Beyond inflating standard errors, clustering can also introduce confounding. If a cluster-level variable is associated with both the exposure and the outcome, it acts as a confounder. Failure to account for the clustering structure means this confounding is not addressed, which can lead to biased point estimates, beyond incorrect standard errors.
Suppose disease prevalence varies by region, and exposure to a risk factor also varies by region. If we analyse the data without accounting for region (the cluster), the association between exposure and disease will be confounded by regional differences. The estimated exposure effect may be biased upward or downward depending on the direction and magnitude of the confounding.
The magnitude of this bias depends on the correlation between the predictor and the cluster-level confounder. Stronger correlations produce greater bias.
1. In simulations with binary outcomes and moderate ICC, ignoring clustering:
2. How can clustering lead to confounding?
3. The inflation of Type I error due to clustering depends on:
Reflection
Why might even a small ICC (e.g., 0.02) be problematic in a large cluster randomized trial with 100 participants per cluster? Calculate the design effect and discuss the implications.
Methods for Dealing with Clustering
Introduction and Overview
From the problem to the toolkit. Earlier sections established that clustering is common, that ignoring it inflates Type I error, and that simulations make the magnitude undeniable. This section turns to the menu of solutions: fixed effects, correction factors, robust (sandwich) variance estimation, design-based survey methods, generalised estimating equations (GEE) (Liang & Zeger, 1986; Zeger & Liang, 1986), and mixed (random-effects) models (Laird & Ware, 1982; Diez Roux, 2000). Each has different strengths, different assumptions, and a different way of “paying back” the variance that clustering takes away. Treat this section as a roadmap. We will return to mixed models for continuous outcomes in a later lesson, mixed models for discrete outcomes in a later lesson, and repeated-measures designs in a later lesson.
Learning Objectives
- Detect clustering using visual inspection, ICC estimation, and likelihood ratio tests for random-effects terms.
- Compare fixed-effect, correction-factor, robust-variance, and survey-weighted approaches to clustered data.
- Distinguish marginal (population-averaged) from conditional (cluster-specific) interpretations of regression coefficients.
- Outline how generalised estimating equations (GEE) and mixed models address clustering and where each is preferred.
- Choose an analytical strategy based on the number of clusters, the question, and whether cluster-level predictors are of interest.
Detecting Clustering
Before choosing a method for handling clustering, you must first detect and quantify it. Common approaches include visual inspection (e.g., plotting outcomes by cluster), ICC estimation (fitting a random-intercept model to estimate the between-cluster variance), and likelihood ratio tests (comparing models with and without cluster-level random effects).
Methods for Handling Clustered Data
Fixed Effects & Stratification
Include cluster indicators as fixed effects in the model. This effectively stratifies the analysis by cluster, adjusting for all cluster-level confounders (both measured and unmeasured). However, this approach uses many degrees of freedom (one for each cluster minus one) and does not allow estimation of cluster-level predictor effects.
Best when: There are relatively few clusters, cluster-level confounding is the primary concern, and you do not need to estimate effects of cluster-level variables.
Correction Factor Methods
deff-based correction: Divide test statistics by √deff or multiply standard errors by √deff. This is a simple post-hoc adjustment that requires an estimate of the ICC and the average cluster size.
Overdispersion-based correction: A similar principle using a dispersion parameter estimated from the data. The Pearson or deviance goodness-of-fit statistic divided by its degrees of freedom provides a scale factor that can be applied to the variance-covariance matrix.
Best when: A quick adjustment is needed and a more sophisticated approach is not feasible.
Robust (Sandwich) Variance Estimator
The robust variance estimator does not assume a specific correlation structure within clusters. It provides valid standard errors even if the within-cluster correlation is misspecified (Liang & Zeger, 1986). This makes it very attractive for practical use.
However, it requires a moderate-to-large number of clusters (rule of thumb: at least 20–30). With too few clusters, the sandwich estimator can underestimate the true variance.
Best when: You have enough clusters and want valid inference without specifying the exact correlation structure.
Survey Methods
Survey methods account for complex sampling designs including stratification, clustering, and unequal selection probabilities (weighting). They use design-based inference rather than model-based inference, which means the validity of the analysis depends on the sampling design rather than distributional assumptions.
Available in most statistical software: Stata’s svy commands, SAS PROC SURVEY procedures, R’s survey package.
Best when: The data come from a complex survey design with known selection probabilities.
| Method | Handles Confounding | Min. Clusters | Assumptions | Software |
|---|---|---|---|---|
| Fixed Effects | All cluster-level | Few OK | None for cluster effects | All packages |
| deff Correction | No | Any | Known ICC | Manual calculation |
| Robust Variance | No | ≥20–30 | None for correlation | Stata, R, SAS |
| Survey Methods | Design-based | Varies | Known design | Stata svy, SAS PROC SURVEY, R survey |
Practical Recommendations
Always check for clustering before finalising your analysis. Estimate the ICC, calculate the design effect, and choose a method appropriate to your study design and the number of clusters. When in doubt, use multiple methods and compare results. If the conclusions are consistent across approaches, you can be more confident in your findings.
1. The robust (sandwich) variance estimator:
2. When would fixed effects for clusters be most appropriate?
3. Survey methods for clustered data:
Reflection
You are analyzing data from a multi-site clinical trial with 25 sites and approximately 40 patients per site. Which method(s) for handling clustering would you recommend, and why?
Introduction & The Linear Mixed Model
Introduction and Overview
An earlier lesson ended with a roadmap of methods for clustered data (fixed effects, robust variances, GEE, mixed models, and survey-design adjustments. This lesson takes the deepest single branch of that roadmap and develops it: linear mixed models for continuous outcomes. The mixed-model framework is the backbone for the next two lessons as well, where we extend it to discrete outcomes (a later lesson) and to repeated-measures designs (a later lesson), so the concepts you build here pay forward repeatedly.
The four content sections move from foundations to applications. This section introduces the linear mixed model, the distinction between fixed and random effects, and the random-intercepts specification, the simplest form of the model. A later section extends the framework to random slopes and full hierarchical models, where covariate effects themselves can vary across clusters. A later section tackles the subtle but consequential difference between within-cluster and between-cluster (contextual) effects, and the inferential machinery (REML, likelihood ratio tests) used to fit and compare these models. A later section closes with prediction, BLUPs, residual diagnostics, and the practical questions you face when validating a fitted mixed model.
Learning Objectives
- Distinguish fixed effects from random effects and explain when a mixed model is preferable to ordinary regression.
- Partition total variance into between- and within-cluster components and compute the intraclass correlation coefficient (ICC).
- Write the random-intercept linear mixed model in scalar and matrix form, identifying each parameter.
- Interpret the ICC as both a measure of clustering and a signal of when mixed-model adjustments matter.
Fixed vs. Random Effects
In many epidemiological studies, observations are grouped or clustered: patients within hospitals, students within schools, or repeated measurements within individuals. Linear mixed models (also known as multilevel or hierarchical linear models) handle such data by incorporating both fixed effects and random effects (Laird & Ware, 1982; Curran & Bauer, 2011).
Five classrooms, then random intercepts, then random slopes, then partial pooling. Next ▶ advances scenes.
A 6-scene visualization of mixed-effects models: naive pooled regression ignoring clusters, the reveal of nested classrooms, random intercepts (different starting heights), random slopes (different angles), and partial pooling (shrinkage toward the group mean).
Fixed effects are parameters of primary interest that are constant across groups, namely the population-average effects of predictors. Random effects represent variation across groups or clusters and are modeled as random draws from a probability distribution, typically normal with mean zero.
Variance Components
A fundamental concept in mixed models is the partitioning of total variance into two components: between-group variance (σ²g) and within-group variance (σ²). The between-group variance captures how much group means differ from the overall mean, while the within-group variance captures how much individual observations vary around their group mean.
When to Use Mixed Models
Mixed models are appropriate when your data has a hierarchical or clustered structure; for example, patients nested within clinics, animals nested within herds, or repeated measures nested within subjects. If observations within groups are correlated (i.e., the ICC is non-trivial), ignoring this structure can lead to incorrect inference. Mixed models handle unbalanced data gracefully and can incorporate predictors at both the individual and group levels.
The Linear Mixed Model Equation
The random intercept model extends ordinary linear regression by adding a group-specific random deviation to the intercept (Laird & Ware, 1982):
In this model, each group has its own intercept: β0 + ugroup, where ugroup ~ N(0, σ²g) and εi ~ N(0, σ²). The random intercept ugroup captures how much a particular group’s mean deviates from the overall intercept β0.
The Intraclass Correlation Coefficient (ICC)
The ICC measures the proportion of total variance that is attributable to between-group differences:
An ICC close to 0 means observations within groups are no more similar than observations from different groups. An ICC close to 1 means most of the variance is between groups, and observations within the same group are very similar.
Two readings of the ICC help it stick. First, it is exactly the correlation you would expect between two patients drawn from the same clinic, which is why a larger ICC signals stronger clustering. Second, it tells you when clustering is worth modelling at all. Using the running example, a between-clinic variance near 65 and a residual (within-clinic) variance near 300 give an ICC of 65 / (65 + 300), which is close to 0.18, so roughly a sixth of the variation in blood pressure tracks which clinic a patient attends. An ordinary regression that ignored the clinics would treat those correlated patients as independent and report standard errors that are too small.
lme4::lmer()
The clustered dataset phaa_clinics.csv (30 clinics, ~960 patients) carries forward from an earlier lesson. The continuous outcome is sbp. (1 | clinic_id) says "give every clinic its own intercept, drawn from a Normal." The full annotated script is in r-activities/HSCI_410_Lesson_10_Mixed_Models_for_Continuous_Data.R.
library(lme4); library(lmerTest); library(performance)
clinics <- read.csv("phaa_clinics.csv", stringsAsFactors = FALSE)
clinics$clinic_id <- factor(clinics$clinic_id)
clinics$clinic_urban <- factor(clinics$clinic_urban,
levels = c("rural","urban"))
clinics$smoker <- factor(clinics$smoker, levels = c("No","Yes"))
# 1. Null model: variance partitioning
m0 <- lmer(sbp ~ 1 + (1 | clinic_id), data = clinics)
icc(m0)
# 2. Add patient-level fixed effects
m1 <- lmer(sbp ~ age + smoker + bmi + female + (1 | clinic_id),
data = clinics)
# 3. Add cluster-level fixed effects (clinic_urban, clinic_size)
m2 <- lmer(sbp ~ age + smoker + bmi + female
+ clinic_urban + scale(clinic_size)
+ (1 | clinic_id),
data = clinics)
summary(m2)
icc(m2)
# 4. Is the random intercept needed?
ranova(m2)
# 5. Random slope: does the smoker effect vary by clinic?
m3 <- lmer(sbp ~ age + smoker + bmi + female + clinic_urban + scale(clinic_size)
+ (1 + smoker | clinic_id), data = clinics)
anova(m2, m3) # LRT: random-intercept-only vs random-slope
Why lmerTest. Plain lme4 hides p-values for fixed effects (the df are uncertain). lmerTest adds Satterthwaite-corrected p-values that are good enough for most reports. The contextual-effects trick (splitting age into its clinic-mean and within-clinic deviation) is in the full activity file; it lets you separate "older patients have higher SBP" from "clinics with older patients have higher SBP."
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 summary(m0) Random effects table, report the between-clinic variance (sigma^2_u) and residual variance (sigma^2). Compute and confirm icc(m0) = u^2 / (u^2 + sigma^2). What fraction of total SBP variance lies between clinics?
2. Compare icc(m0) to icc(m2). After adding the patient- and clinic-level fixed effects, did the between-clinic variance shrink? What does that tell you about how much of the original clustering was explained by clinic_urban and clinic_size?
icc(m2) typically drops to ~0.10 after adding patient-level (age, sex, BMI) and clinic-level (urban, size) fixed effects, down from 0.18 in m0. The shrinkage of ~0.08 in ICC reflects how much of the original between-clinic variance was explained by the clinic-level covariates, about half. Residual ICC of 0.10 says clinics still differ in ways not captured by these covariates (perhaps quality of care, patient socioeconomic profile, regional factors).3. From anova(m2, m3), what is the chi-square and p-value for adding a random slope on smoker? Should you keep the random slope, or stick with the random-intercept-only model? Why is the simpler model preferred when the LRT is non-significant?
anova(m2, m3) for adding a random slope on smoker typically returns a χ² around 1–3 with p > 0.10, which is non-significant. Because the extra slope variance sits at its lower boundary of zero, that reported p-value is if anything conservative, so the boundary correction from this lesson would only flip a borderline result, not a clearly non-significant one like this. Keep the simpler random-intercept-only model. The non-significant LRT means the data don't provide strong evidence that the smoking effect varies meaningfully between clinics; the additional random-effect parameter doesn't improve fit enough to justify its loss of df. Simpler models are preferred because (a) fewer parameters to estimate, more stable; (b) easier to interpret and communicate; (c) avoid overfitting to clinic-specific noise; (d) match the principle of parsimony, explaining the data with the fewest assumptions.Matrix Notation
In matrix form, the linear mixed model is written as:
Here, X is the design matrix for fixed effects, β is the vector of fixed effect coefficients, Z is the design matrix for random effects, u is the vector of random effects, and ε is the vector of residual errors.
ANOVA-based methods provide simple estimators of variance components by equating observed mean squares to their expected values. While these methods are intuitive and historically important, they can produce negative variance estimates (which are set to zero in practice). Likelihood-based methods (ML and REML) are generally preferred as they constrain variance estimates to be non-negative and handle unbalanced data more naturally.
Consider a study of milk production across 50 dairy herds with varying numbers of cows per herd. A random intercept model with herd as the grouping factor would estimate σ²g (between-herd variance) and σ² (within-herd variance). If σ²g = 200 and σ² = 800, the ICC = 200/(200+800) = 0.20, meaning 20% of the total variation in milk production is attributable to differences between herds.
The standard random intercept model assumes: (1) random effects u are normally distributed with mean 0 and variance σ²g; (2) residuals ε are normally distributed with mean 0 and variance σ²; (3) random effects and residuals are independent of each other and of the predictors; (4) conditional on the random effects, observations within the same group are independent.
1. In a linear mixed model, random effects represent:
2. The ICC in a random intercept model equals:
3. In the model Y = Xβ + Zu + ε, the term Zu represents:
Reflection
Why might treating group effects as random rather than fixed be advantageous? Think about a study with many groups. What practical benefits does the random effects approach offer?
Random Slopes & Hierarchical Models
Introduction and Overview
From shifting intercepts to shifting effects. An earlier section used random intercepts to let each cluster have its own baseline level, a natural fix for the “clusters differ on average” problem flagged in an earlier lesson. But what if the relationship between a predictor and the outcome also varies across clusters? Random slopes generalise the framework to allow that. This section walks through random-slope specifications, full hierarchical (multi-level) models, and the cross-level interactions that emerge when we let cluster-level variables modify individual-level slopes, a setup central to multi-site trials, school-effects research, and longitudinal cohort designs.
Learning Objectives
- Specify a random-slopes model and explain how it generalises the random-intercepts model.
- Interpret the covariance matrix of random effects, including the variance and intercept-slope covariance terms.
- Construct hierarchical (multi-level) models with predictors at level 1 and level 2.
- Recognise cross-level interactions and explain when adding random slopes is empirically justified.
Random Slopes
A random intercept model assumes that the effect of each predictor is the same across all groups; only the baseline level (intercept) varies. A random slopes model relaxes this assumption by allowing the effect (slope) of one or more predictors to vary across groups as well (Bates, Mächler, Bolker, & Walker, 2015).
Here, u0j is the random intercept for group j and u1j is the random slope for group j. Each group effectively has its own regression line with intercept (β0 + u0j) and slope (β1 + u1j).
In plain terms, a random intercept lets each clinic’s line sit higher or lower while every line keeps the same tilt, so the fitted lines stay parallel. A random slope lets the tilt itself change from clinic to clinic, so a predictor can matter more in some clinics than in others. Picture a stack of parallel lines that you are now allowed to rotate one at a time: some steepen, some flatten, and a few may even swing the other way.
Random Intercept Model
In the random intercept model, all groups share the same slope for each predictor but have different baseline levels. The regression lines for different groups are parallel, shifted up or down by their random intercept. This is appropriate when you believe the effect of a predictor is consistent across groups but groups differ in their overall level of the outcome.
Random Intercept + Random Slope Model
In this extended model, each group can have both a different intercept and a different slope. The regression lines are no longer parallel: they can fan out, converge, or cross. This model requires estimating additional parameters: the variance of the random slope (σ²u1) and the covariance between the random intercept and slope (σu01). It is more flexible but also more complex and requires sufficient data.
The Covariance Matrix of Random Effects
When a model includes both random intercepts and random slopes, the random effects for each group are typically assumed to follow a bivariate normal distribution. The covariance matrix of the random effects includes three parameters: the variance of the random intercept (σ²u0), the variance of the random slope (σ²u1), and the covariance between them (σu01).
A positive covariance means groups with higher intercepts tend to have steeper slopes; a negative covariance means the opposite. This covariance should generally be estimated rather than assumed to be zero.
Hierarchical Model Interpretation
Random slopes models are sometimes called hierarchical or multilevel models because predictors can have effects at each level of the hierarchy. At the individual level, predictors explain variation within groups; at the group level, predictors or random effects explain variation between groups. This formulation shows that each predictor can enter as a fixed effect, a random effect at the group level, or both.
Imagine a multi-center clinical trial measuring blood pressure reduction across 30 hospitals. A random intercept model would allow hospitals to differ in their patients’ baseline blood pressure. A random slopes model would additionally allow the treatment effect itself to vary across hospitals, since some hospitals might show a larger treatment effect than others due to differences in patient populations, adherence, or clinical practice. The variance of the random slope tells you how much the treatment effect varies across sites.
Practical Considerations
Models with multiple random effects can have many parameters in the covariance matrix, and identifiability can become an issue. Practical parsimony is important: only include random effects for which there is theoretical justification and sufficient data. Adding unnecessary random effects can lead to convergence problems, unstable estimates, or singular covariance matrices.
1. A random slopes model allows:
2. In a random slopes model, the covariance between random intercept and slope:
3. Random slope models are sometimes called hierarchical models because:
Reflection
Consider a multi-center clinical trial where the treatment effect might vary across centers. What would a random slopes model for the treatment effect tell you that a random intercept model would not?
Contextual Effects & Statistical Analysis
Introduction and Overview
Within, between, and the gap between them. Once we let intercepts and slopes vary across clusters, a subtler issue surfaces: the same predictor can have a different effect depending on whether you look at variation within clusters or between them. Income predicts health one way at the individual level and another way at the neighbourhood level, and conflating the two is a common source of misleading conclusions. This section formalises that distinction (contextual effects), then turns to the statistical machinery for fitting and comparing mixed models: REML vs ML, likelihood-ratio tests for variance components, and the practical decisions that go with them. These ideas extend almost verbatim into later lessons.
Learning Objectives
- Define contextual effects and explain how within-group and between-group slopes can diverge.
- Apply group-mean centering to separate within-cluster from between-cluster effects.
- Distinguish ML from REML estimation and choose appropriately for fixed-effect vs variance-component inference.
- Use likelihood-ratio tests, including boundary corrections, to compare nested mixed models.
- Recognise the ecological and atomistic fallacies that follow from ignoring the contextual distinction.
Contextual Effects
A contextual effect occurs when a predictor measured at the individual level has a different effect depending on whether you examine variation within groups or between groups (Curran & Bauer, 2011). For a contextual effect to exist, two conditions must hold: (1) the predictor must vary both between and within groups, and (2) the within-group and between-group slopes must differ.
Understanding Contextual Effects
Imagine studying the relationship between income and health across neighborhoods. At the individual level (within a neighborhood), higher income might improve health modestly. But the neighborhood-level (between-group) effect of average income could be much stronger because wealthier neighborhoods have better infrastructure, cleaner environments, and more health services. The difference between these two slopes is the contextual effect: the additional benefit of living in a high-income neighborhood beyond one’s own income level.
Group-Mean Centering
To separate within-group and between-group effects, we can use group-mean centering. This replaces the original predictor X1i with:
The centered variable Z1i captures purely within-group variation (how an individual differs from their group mean). The group mean X1,group can then be included as a separate predictor to capture between-group variation.
Here, βW is the within-group effect and βB is the between-group effect. If βW ≠ βB, a contextual effect is present. Ignoring this distinction can lead to the ecological fallacy (wrongly attributing group-level associations to individuals) or the atomistic fallacy (wrongly attributing individual-level associations to groups).
Estimation Methods: ML vs. REML
Maximum Likelihood (ML)
ML estimation simultaneously estimates all parameters (fixed effects and variance components) by maximizing the full likelihood. However, ML does not account for the degrees of freedom used in estimating fixed effects, which leads to downward-biased estimates of variance components, analogous to dividing by n instead of n−1 in sample variance estimation (Patterson & Thompson, 1971). ML is required when comparing models with different fixed effects structures (e.g., likelihood ratio tests for fixed effects).
Restricted Maximum Likelihood (REML)
REML estimation adjusts for the degrees of freedom lost in estimating fixed effects by restricting the likelihood to a subspace orthogonal to the fixed effects (Patterson & Thompson, 1971). This produces less biased variance component estimates, especially when the number of groups is small. REML is generally the preferred method for estimating variance components. However, REML log-likelihoods are not comparable across models with different fixed effects.
Inference in Mixed Models
Wald tests are commonly used to test individual fixed effects. These are approximate tests that rely on asymptotic theory. For finite samples, approximations such as the Satterthwaite or Kenward–Roger methods provide better reference distributions (t or F) by estimating effective degrees of freedom (Kenward & Roger, 1997). These corrections are especially important when the number of groups is small.
To test whether a variance component is significantly different from zero (e.g., H0: σ²g = 0), we use a likelihood ratio test comparing the model with and without that random effect. However, because the null value (0) is on the boundary of the parameter space, the standard χ² reference distribution is too conservative. The recommended correction is to halve the P-value from the χ² test.
When comparing models with different random effects but the same fixed effects, use REML-based likelihood ratio tests (with P-value halving for boundary tests). When comparing models with different fixed effects, use ML-based likelihood ratio tests or information criteria (AIC, BIC). Always ensure that models being compared are nested and fit to the same data.
1. A contextual effect exists when:
2. REML estimation is generally preferred over ML because:
3. When testing whether a random effect variance is significantly different from zero:
Reflection
Explain in your own words why the ecological fallacy can occur when contextual effects are ignored. Give an example from epidemiology where the group-level and individual-level associations might differ.
Prediction, Residuals & Diagnostics
Introduction and Overview
From estimation to validation. Earlier sections walked through specifying, fitting, and interpreting linear mixed models. This final section addresses the questions that follow: how do we predict outcomes for individuals (with and without their cluster-specific deviation), what do BLUPs tell us about the clusters themselves, and how do we know whether the model fits? Mixed models have two layers of residuals, level-1 (within-cluster) and level-2 (between-cluster), and validating both is essential before drawing inferential conclusions. The diagnostic logic you build here transfers directly to the discrete-outcome and repeated-measures extensions in later lessons.
Learning Objectives
- Compute and interpret BLUPs (empirical Bayes estimates) of cluster-level random effects.
- Explain the shrinkage factor and why small clusters are pulled more strongly toward the overall mean.
- Distinguish level-1 (within-cluster) from level-2 (between-cluster) residuals and use both for diagnostics.
- Apply Box-Cox or alternative transformations to address non-normality of continuous outcomes in mixed models.
- Validate a fitted mixed model before reporting fixed-effect inferences.
BLUPs: Best Linear Unbiased Predictors
In a mixed model, the random effects u are not directly observed: they are latent variables. We estimate them using BLUPs (Best Linear Unbiased Predictors), which are the predicted values of the random effects conditional on the observed data (Laird & Ware, 1982; Bates et al., 2015).
The Shrinkage Factor
BLUPs are weighted averages of the group-specific estimate and the overall mean. The amount of shrinkage depends on the group size and the ICC:
When m (the group size) is large, the shrinkage factor approaches 1 and the BLUP closely approximates the raw group mean. When m is small, the factor is closer to 0 and the BLUP is pulled substantially toward the overall mean.
Partial pooling: the middle ground
Shrinkage is easiest to picture as a compromise between two extremes. One extreme is no pooling, where every cluster is fitted on its own data alone, so a three-patient clinic’s noisy average is trusted completely. The other extreme is complete pooling, where the clusters are ignored and a single line is fitted to everyone, as if the clinics were identical. A mixed model does neither. It applies partial pooling: each cluster’s estimate is a weighted blend of its own mean and the overall mean, and the weight is the shrinkage factor above. Data-rich clusters stay close to their own mean, while data-poor clusters lean on the crowd, which is what borrowing strength means in practice.
Consider a random intercept model for patient outcomes across hospitals. Suppose σ²g = 5 and σ² = 20. For a hospital with 100 patients: shrinkage factor = 5/(5 + 20/100) = 5/5.2 = 0.96, so the BLUP is very close to the hospital’s raw mean. For a hospital with only 4 patients: shrinkage factor = 5/(5 + 20/4) = 5/10 = 0.50, so the BLUP is pulled halfway toward the overall mean. This borrowing of strength from other groups is a key advantage of mixed models.
Residuals in Mixed Models
Mixed models produce multiple sets of residuals, one for each level of the hierarchy:
- Individual-level residuals (ε): the difference between observed values and the group-specific predictions (using BLUPs)
- Group-level residuals (u): the BLUPs themselves, representing how each group deviates from the overall mean
Model Diagnostics
Checking model assumptions in mixed models involves examining residuals at each level of the hierarchy. Variance explained at each level can also be summarised using marginal and conditional R² statistics (Nakagawa & Schielzeth, 2013). A recommended strategy is to work from the highest hierarchical level downward:
Practical Diagnostic Advice
Start by examining group-level residuals (BLUPs): check for normality using Q-Q plots and look for influential groups. Then examine individual-level residuals: check normality, homoscedasticity, and look for outliers. Working top-down helps identify whether problems originate at the group level rather than being caused by a few individual outliers within groups. Also check that residuals at each level are uncorrelated with predictors and fitted values.
Box-Cox Transformation for Mixed Models
When model assumptions (normality, homoscedasticity) are violated, a Box-Cox transformation of the response variable may help. In mixed models, the procedure involves computing transformed Y values for a range of λ values, fitting the same model to each, and comparing log-likelihoods. Crucially, ML estimation (not REML) must be used for comparing log-likelihoods across different λ values, because REML likelihoods are not comparable when the response variable changes.
1. BLUPs (Best Linear Unbiased Predictors) exhibit shrinkage, meaning:
2. When checking residuals in a mixed model, it is recommended to:
3. The Box-Cox transformation in mixed models:
Reflection
A random intercept model for hospital costs has a group of 5 hospitals with only 3 patients each and another group of 20 hospitals with 100 patients each. How would shrinkage affect the BLUP estimates differently for these two groups?
Introduction & Logistic Regression with Random Effects
Introduction and Overview
An earlier lesson developed mixed models for continuous outcomes: random intercepts, random slopes, contextual effects, BLUPs, and diagnostics. This lesson extends every one of those ideas to discrete outcomes: binary (logistic), count (Poisson and negative binomial), ordinal, and multinomial. The framework you built last lesson carries over almost verbatim, but the link function, the likelihood, and the interpretation of effects all shift, and a new question becomes important: do you want a conditional (subject-specific) effect or a marginal (population-average) one?
The four content sections progress from the simplest extension to the practical realities of fitting and validating GLMMs. This section introduces the GLMM by way of logistic regression with a random intercept, the discrete analogue of the random-intercept linear mixed model. A later section generalises to count, ordinal, and categorical outcomes, and confronts the conditional-vs-marginal interpretation head on. A later section turns to estimation: penalised quasi-likelihood, Laplace approximation, adaptive Gauss–Hermite quadrature, MCMC, the menu of techniques used because no closed-form likelihood exists. A later section closes with inference, diagnostics, and a tour of related random-effects extensions (random-effects survival models, latent-variable formulations) that connect this lesson to the rest of the course.
Learning Objectives
- Specify a logistic GLMM with a random intercept and identify the role of the link function on the linear predictor.
- Distinguish subject-specific (conditional) from population-averaged (marginal) effects in non-linear mixed models.
- Apply the SS-to-PA conversion formula for logistic models and explain why the two coefficients differ.
- Interpret measures of cluster heterogeneity (median odds ratio, ICC on the latent scale) in a binary GLMM.
The Generalised Linear Mixed Model (GLMM)
Generalised linear mixed models (GLMMs) extend generalised linear models (GLMs) by adding random effects to the linear predictor (Stiratelli, Laird, & Ware, 1984; Breslow & Clayton, 1993). Just as linear mixed models allowed us to handle clustered continuous data, GLMMs handle clustered discrete data (binary, count, ordinal, and multinomial outcomes) while accounting for the correlation within clusters (Bolker et al., 2009).
Key Concept
The core idea of a GLMM is straightforward: take the linear predictor from a GLM and add random effects. For a logistic regression with a random intercept, the model becomes: logit(pij) = β0 + β1X1ij + ugroup(i), where ugroup(i) ~ N(0, σ²g). The random effect u captures between-cluster variation in the log-odds of the outcome.
Subject-Specific vs. Population-Averaged Interpretation
A critical distinction in GLMMs for discrete data is between subject-specific (SS) and population-averaged (PA) interpretations of the model parameters (Zeger, Liang, & Albert, 1988; Heagerty & Zeger, 2000). This distinction does not arise in linear mixed models but is fundamental for logistic and other non-linear models.
Because of the non-collapsibility of the odds ratio (averaging the odds ratio across clusters does not return the within-cluster odds ratio), SS coefficients are always larger in magnitude than PA coefficients. The approximate conversion formula is:
Consider a study of antibiotic resistance in cattle herds. A logistic GLMM with a random intercept for herd yields βSS = 0.85 for a treatment variable, with σ²g = 1.2. The SS odds ratio is exp(0.85) = 2.34: within any given herd, treatment more than doubles the odds of resistance. The median odds ratio (Larsen & Merlo, 2005) provides a complementary summary of between-herd heterogeneity.
Converting to PA: βPA ≈ 0.85 / √(1 + 0.346 × 1.2) = 0.85 / 1.19 = 0.71. The PA odds ratio is exp(0.71) = 2.03: across the population of herds, the average effect is smaller. The SS estimate is larger because it conditions on a specific cluster.
In plain words: which effect am I reading?
Picture one clinic. The subject-specific effect answers a within-clinic question: take two patients in that same clinic who differ only in the exposure, and ask how much their odds differ. The population-averaged effect answers a whole-population question: averaging across every clinic, how do the odds compare between exposed and unexposed people? The two numbers part ways because the logit curve is bent, and the average of a bent curve is not the same as the curve evaluated at the average. Averaging many steep subject-specific curves, each sitting at a different clinic's baseline, yields a gentler overall curve, so the population-averaged effect lands closer to no effect. A working rule: report the subject-specific effect when you advise one individual inside a known cluster, and the population-averaged effect when you plan for a whole population.
Measures of Cluster Heterogeneity
Median Odds Ratio (MOR)
The Median Odds Ratio quantifies between-cluster heterogeneity on the odds ratio scale. If you randomly select two clusters and compare a person from the higher-risk cluster to a person from the lower-risk cluster (with the same covariates), the MOR is the median of that odds ratio distribution.
An MOR of 1 means no between-cluster variation. Larger values indicate greater heterogeneity. The MOR allows direct comparison of the importance of cluster-level variation relative to fixed-effect odds ratios.
To make the scale concrete: an MOR of 2 means that if you pick two clusters at random and compare an otherwise-identical patient in each, the typical (median) ratio of their two odds is about 2, a gap as large as a moderately strong fixed-effect predictor. Reporting the MOR next to the fixed-effect odds ratios lets a reader judge whether where a patient is treated matters as much as the measured risk factors.
ICC for Binary Data
For binary outcomes, the latent variable ICC uses the fact that the individual-level variance on the logistic scale is π²/3 ≈ 3.29:
This provides an estimate of the proportion of total variance (on the latent scale) attributable to between-cluster differences.
The Latent Variable Approach
The binary outcome can be thought of as the result of thresholding a continuous latent variable. If the latent variable exceeds a threshold, the outcome is 1; otherwise, it is 0. In the logistic model, the individual-level error follows a standard logistic distribution with variance π²/3. This framework provides the basis for both the ICC calculation and the SS-to-PA conversion.
1. In a logistic GLMM, subject-specific (SS) coefficients are:
2. The Median Odds Ratio (MOR) measures:
3. The ICC for binary outcomes using the latent variable approach uses:
Reflection
Why does the distinction between subject-specific and population-averaged estimates matter in practice? Think of a scenario where you would prefer one interpretation over the other.
GLMMs for Count, Binary & Categorical Data
Introduction and Overview
From logistic to the full discrete-outcome family. An earlier section used logistic regression with a random intercept to introduce the GLMM. This section extends the framework outward to count outcomes (Poisson and negative binomial GLMMs, revisiting the count-data tools from an earlier lesson with clustering layered on top), ordinal outcomes (cumulative-link mixed models, an earlier lesson with random effects), and multinomial outcomes. Throughout, the conceptual difference between subject-specific and population-average effects becomes central: in non-linear models the two are not the same, and which one a stakeholder cares about should drive your modelling choice.
Learning Objectives
- Fit Poisson and negative-binomial GLMMs and interpret random effects as multiplicative cluster-level rate modifiers.
- Choose between normal and gamma random effects, and recognise when negative-binomial GLMMs handle residual overdispersion.
- Extend the GLMM framework to ordinal (cumulative-link mixed) and multinomial outcomes.
- Decide between conditional and marginal effects depending on the substantive question and stakeholder.
Poisson Regression with Random Effects
For count outcomes, Poisson regression with random effects models the log of the expected count as a function of predictors plus random effects:
Because the random effects enter on the log scale, they translate to multiplicative effects on the rate scale: μ = exp(Xβ) × exp(u). The group-level multipliers exp(u) follow a log-normal distribution when u is normally distributed.
Poisson with Normal Random Effects
The standard GLMM approach uses normally distributed random effects on the log scale. The group-level effects νgroup = exp(ugroup) are then log-normally distributed. This is the most common parameterisation in software.
This approach is flexible and can accommodate multiple levels of random effects, random slopes, and complex covariance structures, just like the linear mixed model framework.
Poisson with Log-Gamma Random Effects
An alternative parameterisation uses gamma-distributed random effects on the rate scale (equivalently, log-gamma on the log scale). When u follows a log-gamma distribution, the marginal distribution of counts has a convenient closed form.
This connection leads directly to the negative binomial distribution: a Poisson model with gamma-distributed rates yields negative binomial counts.
Negative Binomial as a Random Effects Model
The negative binomial distribution can be interpreted as a Poisson-gamma mixture: counts follow a Poisson distribution, but the rate varies across units according to a gamma distribution. This naturally accounts for overdispersion (variance > mean).
The negative binomial can be extended with additional random effects at higher levels, combining the overdispersion correction with explicit hierarchical structure.
| Model | Random Effect Distribution | Marginal Distribution | Key Feature |
|---|---|---|---|
| Poisson + Normal RE | Normal on log scale | No closed form | Standard GLMM; flexible |
| Poisson + Gamma RE | Gamma on rate scale | Negative binomial | Closed-form marginal |
| Negative Binomial | Implicit gamma | Negative binomial | Handles overdispersion |
The clustered dataset phaa_clinics.csv (carried forward from earlier lessons) has a binary outcome referred (1 = referred to a specialist). Same predictors as before but a binary outcome means a logistic GLMM. The full annotated script is in r-activities/HSCI_410_Lesson_11_Mixed_Models_for_Discrete_Data.R.
library(lme4); library(performance); library(geepack)
clinics <- read.csv("phaa_clinics.csv", stringsAsFactors = FALSE)
clinics$clinic_id <- factor(clinics$clinic_id)
clinics$clinic_urban <- factor(clinics$clinic_urban,
levels = c("rural","urban"))
clinics$smoker <- factor(clinics$smoker, levels = c("No","Yes"))
# 1. Logistic GLMM (subject-specific)
m_glmm <- glmer(referred ~ age + female + smoker + bmi + clinic_urban
+ (1 | clinic_id),
data = clinics,
family = binomial,
control = glmerControl(optimizer = "bobyqa"))
summary(m_glmm)
exp(fixef(m_glmm)) # subject-specific ORs
icc(m_glmm) # latent-scale ICC
# 2. GEE (population-averaged)
m_gee <- geeglm(referred ~ age + female + smoker + bmi + clinic_urban,
id = clinic_id, data = clinics,
family = binomial, corstr = "exchangeable")
summary(m_gee)
exp(coef(m_gee)) # population-averaged ORs
# 3. Compare side-by-side
cbind(GLMM_OR = exp(fixef(m_glmm)),
GEE_OR = exp(coef(m_gee)))
Subject-specific vs population-averaged. glmer() returns subject-specific ORs ("within the same clinic, two patients differ by ..."). GEE returns population-averaged ORs ("across the population, the average difference is ..."). For non-linear link functions like logit they are NOT the same; pick the one that matches your scientific question.
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(fixef(m_glmm)) and exp(confint(m_glmm, method = "Wald")), report the subject-specific OR (and 95% CI) for smokerYes. Translate it into one sentence that explicitly conditions on the clinic (e.g., "within the same clinic, two patients...").
exp(fixef(m_glmm)) for smokerYes typically returns a subject-specific OR around 1.65, 95% CI roughly (1.30, 2.10). Interpretation, conditioning explicitly: within the same clinic, two patients who differ only in smoking status (one smoker, one non-smoker) differ in their odds of the outcome by a factor of about 1.65. This is a conditional, subject-specific effect: the comparison is between hypothetical patients in the same random-effect group.2. From icc(m_glmm), report the latent-scale ICC. Why does the binary ICC require a special formula (rather than just sigma^2_u / total variance like in linear mixed models)?
icc(m_glmm) typically returns a latent-scale ICC around 0.10–0.15. The binary ICC requires a special formula because the residual variance on the binary scale is the logit's variance π²/3 ≈ 3.29 by convention (not estimated like in linear mixed models); the latent-scale ICC is σ²u / (σ²u + 3.29). In linear mixed models you have an estimable residual variance σ², but in logistic GLMMs the residual variance on the underlying continuous (latent) scale is fixed by the link function, so the ICC depends only on between-cluster variance.3. Compare GLMM ORs vs GEE ORs from cbind(GLMM_OR, GEE_OR). Which set of ORs is larger in magnitude, and why is that expected with a logit link? In one sentence, state when a public-health audience would prefer the GEE interpretation over the GLMM.
GLMMs for Other Discrete Outcomes
While the logit link is most common for binary data, probit and complementary log-log links can also be used in GLMMs. For probit models, the SS-to-PA conversion uses a constant of 1 instead of 0.346: βPA ≈ βSS / √(1 + σ²g). This is because the probit model uses the normal distribution, whose variance is 1.
The proportional odds model for ordinal outcomes can be extended by adding random effects to the latent variable underlying the ordinal categories. The subject-specific interpretation and the latent variable ICC methods from logistic regression apply similarly. Random effects capture cluster-level variation in the propensity to be in higher or lower categories.
Random effects multinomial logistic models are less common and harder to estimate. The computational burden increases because each category (beyond the reference) has its own set of parameters, and the random effects may need to be correlated across categories. Specialised software and careful model specification are required.
Zero-inflated models combine a point mass at zero with a count distribution. Random effects can be added to the count part, the zero-inflation part, or both. This flexibility allows the model to capture clustering in both the probability of being a “structural zero” and in the count process among non-zeros.
Choosing Between Models for Count Data
When faced with overdispersed count data, consider: (1) Is the overdispersion due to unmeasured heterogeneity between known clusters? Use a Poisson GLMM. (2) Is the overdispersion due to general extra-Poisson variation without a clear clustering structure? A negative binomial may suffice. (3) Are there excess zeros beyond what either model predicts? Consider a zero-inflated model. Often, comparing model fit statistics (AIC, BIC) across competing models is the practical approach.
1. In a Poisson GLMM with normal random effects on the log scale, the group-level effects on the rate scale are:
2. The negative binomial distribution can be viewed as:
3. Random effects can be added to proportional odds models for ordinal data by:
Reflection
A researcher finds that a Poisson model for disease counts across 50 communities has significant overdispersion. What are the relative advantages of addressing this with random effects versus using a negative binomial model?
Estimation Methods for GLMMs
Introduction and Overview
Why estimation deserves its own section. Earlier sections specified what a GLMM is and what its coefficients mean. This section focuses on a problem that linear mixed models did not face: the likelihood for a GLMM has no closed form. The integral over the random-effects distribution must be approximated, and the choice of approximation matters: penalised quasi-likelihood is fast but biased (Breslow & Clayton, 1993), the Laplace approximation is the practical default (Bates, Mächler, Bolker, & Walker, 2015), and adaptive Gauss–Hermite quadrature (Pinheiro & Chao, 2006) or MCMC become necessary when high accuracy is required. Knowing which method your software is using (and when it will fail) is essential for trustworthy GLMM inference, especially with rare events or strongly clustered data.
Learning Objectives
- Explain why the GLMM likelihood has no closed form and requires integration over the random-effects distribution.
- Compare penalised quasi-likelihood (PQL), Laplace approximation, and adaptive Gauss–Hermite quadrature in terms of speed, bias, and accuracy.
- Recognise the conditions (rare events, small clusters, strong clustering) under which PQL is unreliable.
- Identify when Bayesian / MCMC estimation is the most defensible choice for a GLMM.
- Read software output critically, tying estimator choice to the trustworthiness of standard errors and p-values.
The Estimation Challenge
Unlike linear mixed models, the likelihood in a GLMM cannot be computed in closed form. The likelihood involves an integral over the random effects distribution that generally has no analytic solution. This is the fundamental computational challenge of GLMMs, and different estimation methods represent different strategies for handling this integral.
Maximum Likelihood (ML) Estimation
ML estimation is the gold standard for GLMMs (Pinheiro & Chao, 2006). It uses Gauss-Hermite quadrature to numerically approximate the integral over the random effects. The integrand is evaluated at carefully chosen points (quadrature points), and a weighted sum provides the approximation.
Adaptive quadrature improves accuracy by centring and scaling the quadrature points based on the mode and curvature of each cluster’s contribution to the likelihood. The number of quadrature points controls accuracy: more points yield better approximations but require more computation. Default values are typically around 7.
ML estimation can be computationally intensive or unstable, especially with multiple random effects (where the dimensionality of integration grows) or with sparse data.
Quasi-Likelihood (QL) Estimation
Quasi-likelihood methods avoid numerical integration by using Taylor expansions to linearise the model, then applying iterative weighted least squares. Key variants include:
- First-order vs. second-order Taylor expansion: second-order is more accurate
- MQL (Marginal Quasi-Likelihood): omits random effect predictions from the working variate; gives PA interpretation
- PQL (Penalised Quasi-Likelihood): includes random effect predictions; gives estimates closer to SS interpretation
PQL with second-order expansion is generally preferred among QL methods (Breslow & Clayton, 1993). However, simulation studies show that first-order MQL can be markedly biased, especially with large variance components or small cluster sizes (Bolker et al., 2009).
Laplace Approximation
The Laplace approximation corresponds to adaptive quadrature with a single quadrature point, the lowest order of adaptive quadrature. It approximates the integral by a normal distribution centred at the mode of the integrand.
Laplace is intermediate in both accuracy and computational cost between full quadrature ML and quasi-likelihood. It is widely available in software (e.g., glmer in R uses Laplace by default; Bates et al., 2015) and provides a good starting point before increasing quadrature points (Pinheiro & Chao, 2006).
| Method | Accuracy | Computation | Interpretation |
|---|---|---|---|
| ML (Adaptive Quadrature) | High (gold standard) | High; increases with random effects | SS |
| Laplace Approximation | Moderate (1 quad point) | Moderate | SS |
| PQL (2nd order) | Moderate | Low | Close to SS |
| MQL (2nd order) | Lower | Low | PA |
| MQL (1st order) | Lowest; may be biased | Lowest | PA |
Practical Recommendations
Check stability: Vary the number of quadrature points and confirm that estimates do not change substantially. Compare methods: Run both ML and QL and check agreement. Use caution: With small clusters, binary outcomes, or large random effects variances, simpler QL methods may be markedly biased; prefer ML or at least second-order PQL. Start simple: Begin with Laplace and increase quadrature points if feasible.
Gauss-Hermite quadrature approximates integrals of the form ∫ f(x) exp(-x²) dx by a weighted sum: ∑ wk f(xk), where xk are the quadrature points and wk are the corresponding weights. The points and weights are chosen to give exact results for polynomial integrands up to a certain degree. For GLMM likelihoods, more quadrature points provide better approximations to the non-polynomial integrand.
Non-adaptive quadrature uses fixed points centred at zero. Adaptive quadrature shifts and scales the points to match the mode and curvature of each cluster’s integrand. This means fewer points are needed for the same accuracy, and the method is more robust when random effects are large or when clusters differ substantially.
Quasi-likelihood methods can produce seriously biased estimates when: (1) random effects variance is large, (2) cluster sizes are small (especially with binary data), (3) prevalence is extreme (close to 0 or 1), or (4) the model has crossed random effects. In these situations, ML estimation with sufficient quadrature points is strongly preferred.
1. Gauss-Hermite quadrature in GLMM estimation is used to:
2. Quasi-likelihood estimation methods:
3. Increasing the number of quadrature points in ML estimation:
Reflection
You are fitting a 3-level logistic GLMM and the ML estimates are unstable. What steps would you take to diagnose the problem and what alternative estimation approaches might you consider?
Inference, Diagnostics & Other Random Effects Models
Introduction and Overview
Closing the loop on GLMMs. Earlier sections covered specification, interpretation, and estimation. This final section addresses the questions that finish the workflow: how do we test fixed effects and variance components when boundaries and approximations complicate standard tests? what residuals make sense in a non-linear mixed model, and how do we read them? and how does the random-effects framework extend to other discrete-outcome problems: random-effects survival models, latent-variable formulations, and zero-inflated count models, that you will see in applied research. The emphasis here is on becoming a critical user of GLMM software output rather than a passive consumer of p-values.
Learning Objectives
- Choose between Wald, likelihood-ratio, and profile-likelihood inference for fixed effects in a GLMM.
- Apply boundary corrections when testing variance components, and recognise when Wald tests near boundaries are misleading.
- Interpret Pearson and deviance residuals in the GLMM setting and use them for cluster-level diagnostics.
- Connect GLMMs to related random-effects extensions: survival, latent-variable, and zero-inflated count models.
- Read GLMM software output critically and identify when reported quantities are unreliable.
Inference for Fixed and Random Effects
Testing and constructing confidence intervals in GLMMs involves the same general principles as in linear mixed models, but with additional complications related to the estimation method used.
For fixed effects, Wald-type tests (based on the estimate divided by its SE) are most common. However, Wald statistics can be unreliable when parameters are near boundary values. Likelihood-based inference (likelihood ratio tests and profile likelihood confidence intervals) is preferred when feasible, but requires ML estimation, not quasi-likelihood.
For random effect variances, the same boundary issues discussed for linear mixed models apply: variance parameters cannot be negative, so the usual chi-square distribution for LR tests may not be appropriate near zero.
Caution with Wald Tests Near Boundaries
Wald statistics assume the sampling distribution of the parameter estimate is approximately normal. This assumption breaks down when parameters are near boundary values (e.g., variance components near zero, or probabilities near 0 or 1). In such cases, confidence intervals based on Wald statistics can include impossible values, and p-values may be misleading. Likelihood-based methods are more reliable.
Alternative Random Effects Models
| Approach | Likelihood | Multi-Level | Individual Predictors | Computational Cost |
|---|---|---|---|---|
| GLMM (normal RE) | Requires integration | Yes | Yes | High |
| Beta-binomial | Closed form | No | Limited | Low |
| Negative binomial | Closed form | With extensions | Yes | Low to moderate |
Practical Guidance
The beta-binomial model is most appropriate when you have grouped binary data (e.g., proportion of animals testing positive in each herd) with only group-level predictors. Its closed-form likelihood makes it computationally simple, and it directly estimates the ICC. However, it cannot accommodate individual-level predictors or multiple hierarchical levels.
Simulation studies consistently show that first-order MQL can be markedly biased, underestimating both fixed effects and variance components (Breslow & Clayton, 1993; Bolker et al., 2009). Second-order PQL performs better but can still be biased with small cluster sizes or large variances. ML with adaptive quadrature is generally the most accurate (Pinheiro & Chao, 2006), though computational constraints may require starting with Laplace approximation.
Start with Laplace (the default in many packages). If feasible, increase to adaptive quadrature with 7+ points and check that estimates are stable. If ML is computationally prohibitive (e.g., many random effects), use second-order PQL and compare results with Laplace. Always report which estimation method was used and, ideally, show sensitivity to the choice.
1. Wald-type statistics for GLMM parameters:
2. The beta-binomial model:
3. First-order quasi-likelihood estimates in GLMMs:
Reflection
Compare the GLMM approach to the beta-binomial approach for modeling clustered binary data. In what situations would each be preferred?
Introduction & Descriptive Approaches
Introduction and Overview
Earlier lessons built up the general framework for clustered data: identifying clustering, quantifying its impact, and modelling continuous and discrete outcomes with random effects. This lesson, the final lesson of this course and of the three-course series, zooms in on a specific kind of cluster that pervades health research: the same subject measured repeatedly over time. Repeated measures designs (clinical trials with follow-up visits, cohort studies tracking biomarkers, growth curves, intensive longitudinal data) introduce structure that the generic mixed-model machinery from earlier lessons can handle, but with an important new ingredient: the temporal ordering of measurements.
The four content sections build the toolkit in stages. This section defines repeated-measures data and develops descriptive approaches (spaghetti plots, mean profiles, and exploratory views that reveal the within-subject correlation structure). A later section contrasts the classic univariate (split-plot ANOVA) and multivariate (MANOVA) approaches against modern alternatives, highlighting their assumptions and breakdowns. A later section turns to linear mixed models with explicit residual correlation structures (compound symmetry, AR(1), Toeplitz, unstructured), the workhorse for continuous longitudinal outcomes. A later section extends to trend models, discrete-outcome longitudinal data, and the marginal (GEE) alternative to mixed models, tying together the conditional/marginal distinction introduced in an earlier lesson.
This lesson is the capstone of the entire three-course series. An earlier course taught you to read epidemiological evidence; an earlier course taught you to design and surveil; this course has taught you to analyse data. Repeated-measures methods are where those three threads converge: every choice you make here (correlation structure, marginal vs. conditional, missingness model) is simultaneously a design judgment, a measurement judgment, and an analytic judgment.
Learning Objectives
- Define repeated-measures data and distinguish balanced, uniform, and equidistant designs from their irregular counterparts.
- Describe how within-subject autocorrelation differs from generic clustering and why time ordering changes the analysis.
- Use spaghetti plots and mean profiles to visualise individual trajectories and the empirical within-subject correlation structure.
- Recognise informative drop-out and missing-data mechanisms that bias longitudinal analyses if ignored.
What Are Repeated Measures?
Repeated measures data arise when multiple measurements are taken over time on the same subjects. This is one of the most common data structures in health sciences research; think of clinical trials where patients are measured at baseline and multiple follow-up visits, or cohort studies that track health outcomes over years (Diggle, Heagerty, Liang, & Zeger, 2002).
Longitudinal studies (which collect repeated measures) differ fundamentally from cross-sectional studies, which measure each subject only once. The key advantage of longitudinal designs is their ability to assess within-subject change over time, making them more powerful for detecting the effects of within-subject predictors.
Why Repeated Measures Require Special Methods
In repeated measures data, observations within the same subject are not independent. Moreover, the time ordering of measurements introduces autocorrelation: measurements closer in time tend to be more strongly correlated than those further apart. This temporal structure means that a simple hierarchical (random intercept) model, which assumes all within-subject correlations are equal, may be inadequate. If this correlation is ignored and the repeated observations are treated as independent, the analysis behaves as though it holds more independent information than it really does, so standard errors come out too small and p-values too optimistic. Special methods are needed to properly account for the pattern of correlations.
Key Terminology
Missing Data and Drop-Outs
Missing data is very common in repeated measures studies. Subjects may miss individual visits (intermittent missingness) or drop out permanently (monotone missingness). The pattern and mechanism of missingness can substantially affect the validity of the analysis (Little, 1995). Methods that can handle unbalanced data (such as mixed models and GEE) are therefore particularly valuable for repeated measures, and multiple imputation under MAR is a widely used complementary tool (Sterne et al., 2009).
Descriptive Approaches
Profile plots (also called spaghetti plots) display each subject's trajectory over time. They reveal patterns of tracking (whether subjects maintain their relative positions), overall trends, and variability. These plots are essential for understanding the data before fitting any model.
Mean plots show the average outcome at each time point, often separated by treatment group. They summarize the overall trend but hide individual variability. Mean plots are useful for visualizing treatment effects over time and identifying non-linear trends.
Examining the correlation matrix of measurements across time points reveals the autocorrelation pattern. If correlations decrease with increasing time distance, an AR(1)-type structure may be appropriate. If correlations are roughly equal, compound symmetry may suffice. The covariance matrix additionally reveals whether variances change over time.
Repeated measures data can be stored in wide format (one row per subject, separate columns for each time point) or long format (one row per measurement, with a time variable). For one patient measured at three visits, wide format is a single row with columns such as bp1, bp2, bp3, whereas long format is three rows that share the same subject id and differ only in a visit column. Most modern statistical software requires long format for mixed models and GEE. Wide format is needed for MANOVA approaches.
Consider a clinical trial where 100 patients are randomized to treatment or placebo, with blood pressure measured at baseline and months 1, 3, 6, and 12. This is a balanced (5 measurements per subject), uniform (same time points), but not equidistant (spacing varies: 1, 2, 3, and 6 months) design. Profile plots reveal that patients’ blood pressures track over time, and the correlation matrix shows correlations declining from 0.80 (adjacent visits) to 0.45 (baseline vs. month 12), clear evidence of autocorrelation.
1. What distinguishes repeated measures data from standard clustered data?
2. A balanced repeated measures design means:
3. Autocorrelation in repeated measures means:
Reflection
Think of a longitudinal study in health sciences. What types of missing data patterns might occur, and how could they affect the validity of your analysis?
Univariate & Multivariate Approaches
Introduction and Overview
Before mixed models, what was the field doing? An earlier section gave us the descriptive picture of repeated-measures data. This section walks through the methods that dominated longitudinal analysis for decades: split-plot ANOVA (univariate, with strong assumptions like compound symmetry/sphericity), MANOVA (multivariate, weaker assumptions but lower power and intolerant of missing data), and summary-statistic approaches that collapse each subject’s trajectory to a single value. Knowing these methods is more than historical: they still appear in legacy literature and teaching, and seeing where they fail motivates the modern approaches in later sections.
Learning Objectives
- Compare separate-time-point, summary-statistic, RM-ANOVA, and MANOVA approaches to longitudinal data.
- State the compound-symmetry / sphericity assumption underlying RM-ANOVA and apply the Huynh–Feldt correction when it is violated.
- Read covariance and correlation matrices and decompose them into variance and correlation components.
- Identify the conditions (balanced data, no missingness, few time points) under which classical methods are still defensible.
Simple Approaches to Repeated Measures
Before turning to complex mixed models, it is worth understanding the simpler methods that have traditionally been used for repeated measures data. These methods either reduce the data to avoid modelling correlations altogether, or make strong assumptions about the correlation structure.
Separate Time Point Analysis
The simplest approach is to analyze each time point independently; for example, running a separate t-test or regression at each visit. This is straightforward but wasteful: it ignores the within-subject correlations and creates a multiple testing problem. If there are m time points, a Bonferroni correction divides α by m, which can be very conservative.
Summary Statistics Approach
A more elegant simple approach is to compute a single summary value per subject, such as the slope of their trajectory, the drop from first to last measurement, or the area under the curve (AUC), and then perform a standard between-subjects analysis on these summaries.
Advantages: Simple, robust to model assumptions about correlation structure, and easy to interpret.
Disadvantages: Loss of information about the temporal pattern, difficulty incorporating within-subject time-varying predictors, and potential loss of power.
Repeated Measures ANOVA
Repeated measures ANOVA treats time as a within-subject factor and tests for differences across time points. However, it assumes compound symmetry: all pairs of time points have the same correlation. This is the same assumption as a random intercept model.
When compound symmetry is violated (which is common with autocorrelated data), the F-test becomes liberal (anti-conservative). The Greenhouse–Geisser and Huynh–Feldt correction factors (ε) adjust the degrees of freedom to account for this violation (Greenhouse & Geisser, 1959; Huynh & Feldt, 1976). When ε = 1, compound symmetry holds perfectly; as ε decreases, the violation is more severe. The underlying assumption can be tested formally with Mauchly's test of sphericity (Mauchly, 1940).
MANOVA (Multivariate Analysis of Variance)
MANOVA treats the entire vector of repeated measurements as a multivariate outcome, making no assumptions about the correlation structure. This is its key advantage over repeated measures ANOVA.
Limitations: Requires completely balanced data with no missing values, cannot easily handle within-subject continuous predictors, and uses wide-format data. It also becomes impractical with many time points.
Covariance and Correlation Matrices
Limitations of Each Approach
Separate time points: Multiple testing, ignores correlations, wasteful of information. Summary statistics: Loses temporal detail, cannot incorporate time-varying covariates. RM ANOVA: Assumes compound symmetry, which is rarely true. MANOVA: Requires complete, balanced data with no missing values. All of these limitations motivate the use of mixed models with flexible correlation structures.
The dataset phaa_repeated.csv tracks 200 patients in a hypothetical wellness trial through 4 visits (months 0, 6, 12, 18). Outcomes: sbp_mmhg (continuous) and adherent (binary). The full annotated script is in r-activities/HSCI_410_Lesson_12_Repeated_Measures_Data.R.
library(lme4); library(lmerTest); library(nlme); library(geepack)
dat <- read.csv("phaa_repeated.csv", stringsAsFactors = FALSE)
dat$id <- factor(dat$id)
dat$arm <- factor(dat$arm, levels = c("control","intervention"))
# 1. Random-intercept mixed model on the continuous outcome
m_lmm <- lmer(sbp_mmhg ~ visit * arm + age + female + (1 | id),
data = dat)
summary(m_lmm)
# 2. Add an AR(1) within-subject correlation structure with nlme
m_lme <- lme(sbp_mmhg ~ visit * arm + age + female,
random = ~ 1 | id,
correlation = corAR1(form = ~ visit | id),
data = dat, na.action = na.omit)
summary(m_lme)
# 3. Compare correlation structures with AIC
m_cs <- update(m_lme, correlation = corCompSymm(form = ~ visit | id))
m_un <- update(m_lme, correlation = corSymm(form = ~ 1 | id))
AIC(m_lme, m_cs, m_un)
# 4. Same trial, binary outcome (adherence) -- GLMM and GEE
m_bin <- glmer(adherent ~ visit * arm + age + female + (1 | id),
data = dat, family = binomial,
control = glmerControl(optimizer = "bobyqa"))
exp(fixef(m_bin)) # subject-specific ORs
m_gee <- geeglm(adherent ~ visit * arm + age + female,
id = id, data = dat, family = binomial,
corstr = "exchangeable")
exp(coef(m_gee)) # population-averaged ORs
Pick the structure deliberately. AR(1) (corAR1) is the natural choice for evenly-spaced visits; corCAR1 handles unequal spacing; corSymm (unstructured) is the most general but estimates the most parameters. lme() handles dropout via likelihood, so you do not have to drop subjects. The visit:armintervention coefficient is the trial's headline number: the additional change in SBP per month attributable to the intervention. The last two lines refit the binary adherence outcome as a population-averaged GEE, so its odds ratios can sit beside the subject-specific ones from the GLMM.
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 summary(m_lmm), report the visit:armintervention coefficient, its SE, and its p-value. Translate it in one sentence: what is the additional change in SBP per month attributable to the intervention vs control?
summary(m_lmm) for visit:armintervention typically returns a coefficient around −0.5 mmHg/month with SE ~0.15 and p < 0.001. Translation: each additional month of follow-up, intervention-arm participants have an SBP change that is 0.5 mmHg more negative than control-arm participants, that is, the intervention's monthly effect on SBP. Over 12 months, the cumulative effect is ~6 mmHg lower SBP than control, a clinically meaningful difference if sustained.2. From AIC(m_lme, m_cs, m_un), which correlation structure has the lowest AIC? Are the differences small (within 2 units) or large? Following the rule "pick the simplest structure with similar AIC," what would you report?
AIC(m_lme, m_cs, m_un) typically shows unstructured (un) with the lowest AIC, but compound symmetry (cs) often within a few units. With the rule "pick the simplest with similar AIC," report compound symmetry as the primary model and unstructured as a sensitivity analysis. Compound symmetry assumes all pairs of visits have the same correlation, a strong assumption but parsimonious. If AIC differences are > 10 between cs and un, switch to unstructured. If < 2, prefer cs.3. From exp(fixef(m_bin)) and exp(coef(m_gee)), compare the subject-specific vs population-averaged ORs for visit:armintervention on the binary adherence outcome. Which is larger in magnitude, and why?
| Approach | Handles Missing Data? | Assumes Equal Correlations? | Time-Varying Covariates? |
|---|---|---|---|
| Separate Time Points | Yes (per time point) | N/A (ignores structure) | Yes |
| Summary Statistics | Partially | No | No |
| RM ANOVA | No | Yes (compound symmetry) | No |
| MANOVA | No | No | No |
| Mixed Models | Yes | Flexible | Yes |
1. The summary statistic approach involves:
2. Repeated measures ANOVA assumes:
3. An advantage of MANOVA over repeated measures ANOVA for repeated measures is:
Reflection
When would you choose a simple summary statistic approach over a mixed model for repeated measures data? What information might you lose by simplifying the analysis in this way?
Linear Mixed Models with Correlation Structure
Introduction and Overview
Where the modern toolkit takes over. An earlier section showed why the classical methods strain when measurement spacing is irregular, missingness is informative, or the within-subject correlation pattern is more complex than “all pairs equally correlated.” Mixed models with explicit residual correlation structures (compound symmetry, AR(1), Toeplitz, unstructured) are the response. They let us model the temporal dependence directly rather than assume it away, handle unbalanced or missing-at-random data gracefully, and combine random effects with structured residuals to capture both subject-level heterogeneity and within-subject autocorrelation. This section is the heart of the lesson.
Learning Objectives
- Specify a linear mixed model with an explicit residual correlation structure and explain how it relaxes the compound-symmetry assumption.
- Distinguish among compound symmetry, AR(1), ARMA(1,1), Toeplitz, and unstructured correlation matrices and identify when each is appropriate.
- Combine random intercepts (and slopes) with structured residuals to capture subject heterogeneity and within-subject autocorrelation.
- Use AIC for non-nested and likelihood-ratio tests for nested correlation structures during model selection.
- Handle unbalanced and irregular-spacing designs that classical methods cannot accommodate.
Beyond Random Intercepts
A random intercept model assumes compound symmetry: all pairs of measurements on the same subject are equally correlated. For most repeated measures data, this assumption is violated because of autocorrelation. We need to extend the mixed model to include explicit correlation structures for the error term ε, the framework formalised in the classic Laird & Ware random-effects model for longitudinal data (Laird & Ware, 1982; Fitzmaurice, Laird, & Ware, 2011).
Choosing a Correlation Structure
The choice of correlation structure is one of the most important decisions in repeated measures analysis. Start by examining the empirical correlation matrix. If correlations clearly decay with increasing time lag, consider AR(1) or ARMA(1,1). If the decay is minimal, compound symmetry may suffice. If the pattern is complex, consider Toeplitz or unstructured. Use AIC to compare non-nested structures and likelihood ratio tests for nested ones.
Key Correlation Structures
Each structure below is a different assumption about how a subject's repeated measurements hang together over time. More flexible assumptions fit a wider range of patterns but cost more parameters, so the aim is the simplest structure that still matches the decay you see in the empirical correlation matrix.
Compound Symmetry (Exchangeable)
All pairs of measurements have the same correlation ρ, regardless of how far apart in time they are. This is the simplest structure and is equivalent to a random intercept model. It has only 1 correlation parameter.
When appropriate: When there is no autocorrelation, that is, the correlation between measurements does not depend on time distance. This is rare in practice for true repeated measures data.
First-order autoregressive: AR(1)
Correlations decay as powers of ρ with increasing time distance: Corr(Yj, Yk) = ρ|j−k|. This produces an exponential decay pattern. It has only 1 parameter (ρ) and is a good default for equally spaced repeated measures.
When appropriate: When the correlation matrix shows a clear pattern of decreasing correlations with increasing time lag, and the decay appears approximately geometric.
ARMA(1,1)
An extension of AR(1) that allows a slower or more flexible decay in correlations. It has 2 parameters and can accommodate patterns where the initial drop in correlation is steep but then levels off.
Toeplitz (Stationary)
Each lag has its own unconstrained correlation. For m time points, there are m − 1 correlation parameters. The structure is “banded”: the correlation depends only on the time lag, not on which specific time points are involved.
When appropriate: When the pattern of decay is irregular and cannot be well approximated by AR(1) or ARMA, but you still believe the correlation depends only on lag distance.
Unstructured
Completely unconstrained correlations and variances for each pair of time points. For m time points, there are m(m+1)/2 parameters. This is the most flexible but requires the most parameters.
When appropriate: Only with few time points and large sample sizes. With many time points, the number of parameters becomes impractical.
| Structure | Parameters | Key Feature | Assumption |
|---|---|---|---|
| Compound Symmetry | 1 | Equal correlations | No autocorrelation |
| AR(1) | 1 | Geometric decay | Equidistant time points |
| ARMA(1,1) | 2 | Flexible decay | Equidistant time points |
| Toeplitz | m − 1 | Lag-specific correlations | Equidistant time points |
| Unstructured | m(m+1)/2 | Completely flexible | None |
Combining Random Effects with Correlation Structures
An important practical consideration is how random effects interact with error correlation structures. Some combinations are redundant and cannot be separately identified:
- Random intercepts + compound symmetry errors = redundant, since both produce the same correlation structure
- Random intercepts + AR(1) errors = useful, since it produces a structure where correlations decay but do not reach zero
- Unstructured errors + random effects = pointless, since the unstructured covariance already captures everything
Covariance pattern models use no random effects at all, relying entirely on the structured covariance of the errors to capture within-subject correlation.
Model Selection
For nested correlation structures (e.g., AR(1) is nested within Toeplitz), use likelihood ratio tests. For non-nested structures (e.g., AR(1) vs. compound symmetry), use AIC or similar information criteria. Models should be compared with the same fixed effects and random effects structure.
In a study with 6 equally-spaced measurements, the empirical correlations ranged from 0.72 (lag 1) to 0.31 (lag 5). An AR(1) model with ρ = 0.73 fit well (AIC = 2,341), while compound symmetry (AIC = 2,398) fit poorly because it predicted equal correlations of 0.52 at all lags. The Toeplitz model (AIC = 2,338) offered a slight improvement over AR(1) but used 4 more parameters. Based on parsimony, AR(1) was selected.
1. The AR(1) correlation structure assumes:
2. Combining random intercepts with compound symmetry errors:
3. For choosing between non-nested correlation structures (e.g., AR(1) vs. Toeplitz), one should use:
Reflection
A study measures blood pressure at 6 monthly visits. The correlation between visits 1 and 2 is 0.60, between visits 1 and 6 is 0.15. Which correlation structure would you initially consider, and why?
Trend Models, Discrete Outcomes & GEE
Introduction and Overview
Pulling the threads together. An earlier section framed within-subject correlation as something to be modelled directly. This section closes the loop on three remaining concerns. First, trend models with random slopes: rather than (or in addition to) structuring the residuals, we let each subject have their own trajectory over time, a particularly intuitive approach when the question is about individual change. Second, discrete longitudinal outcomes: extending the GLMM machinery from an earlier lesson to repeated binary or count measurements. Third, generalised estimating equations (GEE): the marginal alternative to mixed models, which prioritises population-average effects and is robust to mis-specification of the working correlation. Together with an earlier section, this section gives you a complete repeated-measures toolbox.
Learning Objectives
- Fit trend models with random slopes for time and explain how individual trajectory variation induces within-subject autocorrelation.
- Choose linear, polynomial, or log-time parameterisations to match the shape of change over time.
- Apply transition and GLMM-based approaches to discrete repeated-measures outcomes.
- Describe how generalised estimating equations (GEE) target population-averaged effects with a working correlation matrix and a robust sandwich variance.
- Decide between mixed models and GEE based on whether the substantive question is conditional or marginal.
Trend Models with Random Slopes
An alternative to modelling the error correlation directly is to include random slopes for time. This allows each subject to have their own rate of change (growth or decline) over time, with the population-average trend captured by the fixed effect of time.
The variation in individual trajectories naturally induces autocorrelation: subjects who start high and decline slowly will have correlated measurements. This can be sufficient to capture the temporal structure in many datasets, especially when the primary interest is in individual trajectories.
The time variable can be parameterized in different ways: linear (for constant rates of change), polynomial (for curved trajectories), or log-transformed (for rapid early change that levels off).
Discrete Repeated Measures Data
Extending mixed models to discrete outcomes (binary, count) with correlation structures is much harder than for continuous outcomes. The fundamental challenge is that in GLMs, the error term and the linear predictor operate on different scales: the link function transforms the relationship, making it difficult to add correlation structures to the error term in a meaningful way.
When to Use GEE vs. Mixed Models
Use GEE when your research question focuses on population-averaged (marginal) effects; for example, “What is the average treatment effect across the population?” Use mixed models when you want subject-specific (conditional) effects or when the random effects themselves are of scientific interest; for example, “How much do individual subjects vary in their response?”
Transition Models
One approach for discrete repeated measures is the transition model, which includes the previous outcome as a predictor. This captures autocorrelation informally through dependence on the prior outcome.
Here, γ is the log odds ratio comparing those with versus without the previous event. A positive γ means that having the event at the previous time point increases the odds of having it at the current time point.
Generalised Estimating Equations (GEE)
GEE is a population-averaged (marginal) approach that does not require specifying random effects (Liang & Zeger, 1986). Instead, it specifies a “working” correlation structure and uses robust (sandwich) standard errors that provide valid inference even if the working correlation is misspecified.
Trend Models
Trend models add random slopes for time, allowing each subject to have their own trajectory. The random slope induces autocorrelation through the variation in individual trajectories. This approach is particularly natural when the scientific question is about individual growth or decline rates.
Key considerations: Choice of time parameterization (linear, polynomial, log), whether to include both random intercepts and slopes, and whether the induced autocorrelation is sufficient or additional error correlation is needed.
Transition Models
Transition models include the previous outcome Yi,j−1 as a predictor in the model. The coefficient γ represents the log OR for the event given the previous event occurred. This approach is intuitive and can be combined with random effects.
Limitations: Difficult to interpret coefficients for other predictors (they are conditional on the previous outcome), requires careful handling of the first observation (which has no “previous” value), and may not fully capture complex autocorrelation patterns.
Generalised Estimating Equations (GEE)
GEE estimates population-averaged effects using a quasi-likelihood approach. Key features:
- Specifies a working correlation (e.g., exchangeable, AR(1), unstructured)
- With robust (sandwich) SEs, inference is valid even if the working correlation is wrong
- Requires enough clusters/subjects (≥20–30) for reliable sandwich SEs
- Cannot estimate cluster-specific (random) effects; gives only PA estimates
- Better working correlation = more efficient estimates (but always valid with robust SEs)
A study followed 200 patients over 4 visits, recording whether they experienced a symptom (yes/no) at each visit along with a treatment indicator. A GEE model with exchangeable working correlation and robust SEs estimated the treatment OR as 0.65 (95% CI: 0.48–0.88), suggesting treatment reduced the odds of symptoms by 35% on average across the population. The working correlation was estimated as 0.42.
| Feature | GEE | Mixed Models (GLMM) |
|---|---|---|
| Estimate type | Population-averaged (PA) | Subject-specific (SS) |
| Random effects | Not estimated | Estimated |
| Correlation | Working correlation + robust SEs | Explicit random effects / correlation |
| Missing data assumption | MCAR | MAR |
| Minimum clusters | ≥20–30 | Fewer acceptable |
| Best for | PA inference | SS inference, variance components |
1. Trend models with random slopes for time:
2. In a transition model, the previous outcome Yi,j−1 is included to:
3. GEE (Generalised Estimating Equations) provide:
Reflection
Compare the GEE approach and the mixed model approach for analyzing repeated binary outcomes. In what research context would you prefer each approach, and why?
Lesson 6: Comprehensive Assessment
Bringing It All Together
This module forms the final arc of the course, and it opened by retiring the independent-observations assumption that carried the earlier lessons. The first part catalogued where clustering comes from in public-health data (common environments, geography, repeated measurements, study design), quantified the damage with the intraclass correlation, the design effect, and the effective sample size, used simulation to make the consequences visceral, and sketched the toolkit: fixed effects, correction factors, robust variance estimators, design-based survey methods, GEE, and mixed models.
The second part built linear mixed models from the ground up: random intercepts that partition variance into between- and within-cluster components, random slopes and hierarchical models with their covariance structure, contextual effects and group-mean centering, REML versus ML estimation, likelihood-ratio tests with their boundary correction, and the BLUPs, shrinkage, and two-level residual diagnostics that turn estimation into validation. The third part carried that framework across the boundary to discrete outcomes: generalised linear mixed models for binary, count, ordinal, and multinomial data, the distinction between subject-specific and population-averaged effects that has no analogue in the continuous case, the median odds ratio and latent-variable ICC, and the estimation hierarchy from penalised quasi-likelihood through Laplace and adaptive quadrature to MCMC.
The fourth part specialised the framework to the most common kind of cluster in health research, the same subject measured repeatedly over time: descriptive views of longitudinal data, the classical univariate and multivariate methods and where they break down, linear mixed models with explicit residual correlation structures, trend models with random slopes for time, transition models and GLMMs for discrete repeated outcomes, and generalised estimating equations as the marginal alternative. The final assessment asks you to recognise dependent data on sight, compute the quantities that describe it, and choose a defensible modelling strategy, with its interpretation and trade-offs named, for continuous, discrete, and longitudinal outcomes.
Key Takeaways from this lesson
- Clustered data is the norm in public-health research, not a special case; the ICC measures how much of total variance is between clusters, and the design effect deff = 1 + (m−1)ρ translates ICC and cluster size into precision loss, so even small ICCs can drive Type I error rates well above 5%.
- Methods for handling clustering (fixed effects, robust variance, survey weighting, GEE, mixed models) differ in their assumptions, target estimands, and minimum number of clusters; choosing among them requires being clear about whether the question is marginal (population-averaged) or conditional (cluster-specific).
- A linear mixed model partitions total variance into between-cluster (σ²g) and within-cluster (σ²) components; random intercepts give each cluster its own baseline, and random slopes let predictor effects vary across clusters, with the random-effect covariance matrix capturing how intercepts and slopes co-vary.
- Within-group and between-group effects of the same predictor can differ; group-mean centering separates them. REML is preferred for variance-component estimation, ML is required when comparing models that differ in fixed effects, and BLUPs shrink toward the overall mean, more so for small clusters.
- A GLMM adds normally distributed random effects to a generalised linear model's linear predictor; for non-linear links, subject-specific and population-averaged coefficients are not the same, and cluster heterogeneity in binary GLMMs is summarised on the latent scale (latent-variable ICC) or as a median odds ratio.
- The GLMM likelihood requires numerical integration; choose between PQL, Laplace, adaptive Gauss–Hermite, and MCMC based on event rate, cluster sizes, and accuracy needs, and prefer likelihood-ratio and profile-likelihood inference near parameter boundaries.
- Repeated-measures data are clustered data with time ordering: autocorrelation typically decays with lag, so compound symmetry is rarely realistic, and classical methods (RM-ANOVA, MANOVA, summary statistics) break down with unbalanced designs, missingness, or complex correlation patterns.
- Linear mixed models with explicit residual correlation structures (AR(1), ARMA(1,1), Toeplitz, unstructured) model temporal dependence directly; random slopes for time induce autocorrelation through trajectory heterogeneity and are the natural parameterisation when individual change is the substantive question.
- GEE targets population-averaged effects with a working correlation and a sandwich variance; choose it when the question is marginal and robust to correlation mis-specification, and choose mixed models when cluster-specific effects or variance components are of interest.
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 provincial evaluation follows patients in 60 primary-care practices over four annual visits, with a continuous outcome (HbA1c), a binary outcome (an emergency visit in the past year), and some drop-out after the second visit. Reflecting on the whole module, walk through your analytic strategy for both outcomes: how you would detect and quantify the two sources of dependence (practice and repeated measurement), which model you would fit for each outcome and with what random-effect and correlation structure, how you would choose between subject-specific and population-averaged interpretations, which estimation method you would use for the binary outcome and why, and which diagnostics and sensitivity analyses you would report.
Minimum 20 characters required.
Final Knowledge Assessment
1. Clustered data is characterized by:
2. In a study with ICC = 0.05 and 40 subjects per cluster, the design effect is:
3. Which statement about simulation studies on clustering is TRUE?
4. Fixed effects for clusters:
5. A random slopes model differs from a random intercept model by:
6. A contextual effect is detected when:
7. When comparing ML and REML for model selection:
8. Shrinkage in BLUPs is stronger when:
9. In a logistic GLMM, subject-specific (SS) odds ratios are:
10. In a Poisson GLMM, random effects on the log scale translate to:
11. The Laplace approximation in GLMM estimation:
12. When ML estimation for a GLMM is computationally unstable, one should:
13. Repeated measures data differs from standard clustered data primarily because:
14. The AR(1) correlation structure models correlations as:
15. When choosing between GEE and mixed models for repeated measures: