Modelling Dependent Data
Exploratory Data Analysis For Epidemiology
Learning objectives for this lesson:
- Recognise clustered and repeated-measures data, identify the cluster variable, and explain why ignoring the clustering makes standard errors too small, especially for cluster-level predictors.
- Estimate the intracluster correlation coefficient (ICC) from a mixed model with no predictors, and use the design effect and the effective sample size to describe how much information the clustering removes.
- Fit and interpret a linear mixed model with a random intercept in R using
lmer(), reading its fixed effects, its clinic and residual variances, and the ICC after adjustment. - Check a linear mixed model with residual plots, a Q-Q plot of the cluster effects, the number of clusters and a test for a singular fit.
- Fit a logistic mixed model (GLMM) with
glmer()and a GEE model withgeeglm()for a binary outcome, and explain the difference between cluster-specific and population-averaged odds ratios. - Arrange repeated measures in long format, fit a mixed model and a GEE model with a group-by-time interaction, and explain how missed visits affect each analysis.
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, methods and people in this lesson. It can be used as a reference while working through the material or as a review before assessments. Typing in the search box filters the entries.
lmer() for a continuous outcome and glmer() for a binary outcome.
ranef() prints the estimated shift for each cluster.
lmer() and glmer() it is written (1 | cluster).
(1 + time | cluster), which is the same as (time | cluster), and needs more data than a random intercept, so it often fails to converge in small studies.
Random effects in the model summary and by VarCorr().
lmer() from the lme4 package, and loading lmerTest adds p-values for the fixed effects.
isSingular() returns TRUE. It usually means the random-effects part is more complex than the data can support.
glmer(), and its exponentiated fixed effects are cluster-specific odds ratios.
geeglm() from the geepack package, and its odds ratios are population-averaged.
arm:visit, which R includes together with arm and visit when the formula contains arm * visit. It tests whether the outcome changes at a different rate in two groups. In a trial with repeated measures it usually answers the main question.
Recognising Dependent Data
Introduction and Overview
Every regression model in Lessons 3 and 4 assumed that the observations are independent, so that one person's outcome carries no information about another person's outcome. This lesson deals with data in which that assumption fails. Observations are dependent when they share something, such as patients attending the same clinic or the same person measured at several visits. This first section explains how to recognise dependent data, how to measure the strength of the dependence with the intracluster correlation coefficient (ICC) and the design effect, and what goes wrong when the dependence is ignored. The later sections fit models that allow for it.
Learning Objectives
- Recognise clustered data and repeated measures, and identify the variable that defines the clusters.
- Explain why ignoring dependence makes standard errors, confidence intervals and p-values too small.
- Calculate and interpret the intracluster correlation coefficient (ICC), the design effect and the effective sample size.
- Distinguish cluster-level from person-level predictors and explain why cluster-level predictors are affected most.
- Compare an ordinary regression with a mixed model in R and describe how the standard error changes.
What Are Dependent Data?
Data are dependent when observations can be grouped into clusters whose members are more alike than members of different clusters. Two forms are common in public health. In clustered data, people are grouped inside larger units: patients in clinics, students in schools, residents in neighbourhoods, or workers in workplaces. People in the same cluster share a setting, staff, policies and local conditions, so their outcomes tend to be similar. In repeated measures (also called longitudinal data), the same person is measured more than once, and each person's measurements form a cluster. Clusters can also be nested inside one another, such as patients within doctors within clinics, which this lesson mentions only briefly.
Table 5.1 gives four examples of studies that produce dependent data, with the cluster, the observation and the reason why observations in the same cluster are alike.
Table 5.1. Examples of clustered data and repeated measures in public health studies.
| Study | Cluster | Observation | Why observations in a cluster are alike |
|---|---|---|---|
| A survey of patients at 30 clinics | Clinic | Patient | Patients share doctors, practices and a local population. |
| A school-based physical activity program | School | Student | Students share teachers, facilities and a neighbourhood. |
| A household survey of food security | Household | Household member | Members share income, meals and housing. |
| A trial with visits at 0, 6, 12 and 18 months | Person | Visit | Each person brings their own genes, habits and baseline health to every visit. |
The three flip cards below define the cluster, independence and the effective sample size, terms that the rest of the lesson uses repeatedly.
Dependent data therefore arise whenever a study samples people in groups or measures the same people repeatedly, and every method in this lesson needs the variable that identifies the clusters. The next part explains why this grouping matters for a regression model.
Why Dependence Matters
A regression model that assumes independence treats every observation as a separate piece of information. When observations in a cluster are alike, part of what each one says has already been said by the others, so the model overstates how much information it has. The point estimates are often similar, but the standard errors are too small, the confidence intervals too narrow and the p-values too small. In practice, this means that an analysis that ignores clustering can report a statistically significant association that the data do not support (Dohoo, Martin & Stryhn, 2012, Chapter 20).
The clinic data introduced next show how large this effect can be.
The Clinic Data
The first three sections of this lesson use phaa_clinics.csv, a simulated dataset of 966 patients attending 30 primary care clinics, with between 18 and 45 patients per clinic (32.2 on average). It records each patient's age, gender (female = 1 for women), smoking status, BMI, systolic blood pressure (sbp) and whether they were referred to a specialist (referred = 1). Two variables describe the clinic itself: clinic_urban (20 urban and 10 rural clinics) and clinic_size.
Figure 5.1 plots the systolic blood pressure of every patient by clinic, so that the differences between clinic averages can be seen before any model is fitted.

Figure 5.1 shows that a patient’s blood pressure depends partly on the clinic the patient attends. The intracluster correlation coefficient, introduced next, measures how much of the variation in blood pressure lies between clinics.
Measuring Clustering: The Intracluster Correlation Coefficient
The intracluster correlation coefficient (ICC) measures how alike observations in the same cluster are. It divides the total variance of the outcome into a part between clusters (how much the cluster averages differ) and a part within clusters (how much people in the same cluster differ from one another), and it is the share of the total that lies between clusters. Equation 5.1 expresses this share as a ratio of the two variances.
The ICC can also be read as the correlation between the outcomes of two people chosen from the same cluster. Lesson 7 uses a statistic of the same form, the intraclass correlation coefficient, for a different application: measuring the reliability of a score across occasions or raters. Figure 5.2 shows simulated clusters with three values of the ICC.

Worked Example 5.1 applies Equation 5.1 to the clinic data, using the two variances that Activity 5.1 estimates at the end of this section.
Worked Example 5.1: The ICC for Blood Pressure
A mixed model with no predictors (Activity 5.1 below) estimates a between-clinic variance of 22.10 and a within-clinic variance of 104.34. The ICC is 22.10 ÷ (22.10 + 104.34) = 22.10 ÷ 126.44 = 0.175. About 17.5% of the variation in systolic blood pressure lies between clinics, and the blood pressures of two patients from the same clinic have a correlation of about 0.175.
ICCs for clinics, schools and neighbourhoods in health research are often between 0.01 and 0.1, so a value of 0.175 indicates strong clustering. Small ICCs still matter when clusters are large, as the design effect shows.
The ICC of 0.175 measures the strength of the clustering in the clinic data. The next part converts it into a loss of information with the design effect and the effective sample size.
The Design Effect and the Effective Sample Size
The design effect (DEFF) expresses the ICC as a loss of information. It depends on both the ICC and the average cluster size. Equation 5.2 gives the design effect and the effective sample size that follows from it.
For the clinic data, DEFF = 1 + (32.2 − 1) × 0.1748 = 6.45 (using the unrounded ICC), and the effective sample size is 966 ÷ 6.45 = 150. For questions about clinic characteristics, the 966 clustered patients therefore carry about as much information as 150 independent people. The formula also shows why cluster size matters: with 32 people per cluster, even an ICC of 0.05 gives a design effect of 1 + 31 × 0.05 = 2.55, which reduces the effective sample size by more than half. Design effects are also used when planning studies, to inflate the sample size needed for a cluster-sampled survey or a cluster-randomized trial. Students who took HSCI 230 or HSCI 341 met this formula in HSCI 230 Lesson 5, Section 6, and HSCI 341 Lesson 2, Section 5, where it inflates the sample size of a planned study; this section uses the same formula to describe the information lost in an analysis.
The effective sample size of about 150 summarises how much information the clustering removes from the clinic data for questions about clinic characteristics. The next part shows how this loss appears in a regression model that ignores the clinics.
What Goes Wrong When Clustering Is Ignored
The question of whether patients in urban clinics have higher blood pressure than patients in rural clinics shows the problem directly. An ordinary linear regression with lm() treats the 966 patients as independent. A linear mixed model with lmer() gives each clinic its own baseline, as Section 2 explains.
Figure 5.3 compares the two estimates of the urban minus rural difference with their 95% confidence intervals, and Table 5.2 gives the estimates, standard errors and p-values from the two models.

Table 5.2. The urban minus rural difference in systolic blood pressure from an ordinary regression and a linear mixed model.
| Model | Urban minus rural (mmHg) | Standard error | p-value |
|---|---|---|---|
Ordinary regression, lm() | 1.49 | 0.74 | 0.044 |
Mixed model, lmer() | 1.67 | 1.96 | 0.40 |
The ordinary regression suggests a statistically significant difference, and the mixed model shows that the data cannot distinguish urban from rural clinics. The standard error rises from 0.74 to 1.96 because clinic_urban is a cluster-level predictor: it takes one value per clinic, so the 966 patients supply only 30 independent values of it. A person-level predictor such as smoking varies among patients within each clinic, and its standard error changes little when clustering is taken into account (in the Section 2 model, which adds age, gender and smoking, it falls from 0.79 to 0.70, and Section 3 shows a similar pattern for referrals). When a predictor varies within clusters, allowing for clustering can make its estimate more precise, because the model can compare people within the same clinic.
Box 5.1 adds a caution about how this problem is detected in practice.
⚠ Box 5.1: The problem cannot be seen in the ordinary regression output
Nothing in the output of lm() or glm() warns that the observations are clustered. Dependence has to be recognised from the study design and from a variable that identifies the clusters, which is why the first step in any analysis is to ask how the data were collected.
A clustered dataset therefore needs a method that allows for the clustering, and the next part introduces the two families of methods that the lesson uses.
Methods for Dependent Data
Two families of methods are used throughout this lesson. Mixed models add a random effect for each cluster and estimate how much the clusters vary; GEE fits a regression with no cluster effects, so the results describe the population as a whole, and calculates standard errors that allow for the correlation within clusters. Both need a variable that identifies the clusters. Simpler approaches also exist, such as analysing cluster averages or adding a separate indicator variable for every cluster, but they lose information or cannot estimate the effects of cluster-level predictors, and this lesson does not use them.
Table 5.3 lists the three models that the lesson fits, with the outcomes they handle, the R function for each and the sections in which they are used.
Table 5.3. Methods for dependent data used in this lesson.
| Method | Outcome | R function | Used in |
|---|---|---|---|
| Linear mixed model | Continuous | lme4::lmer() (with lmerTest for p-values) | Sections 2 and 4 |
| Generalized linear mixed model (GLMM) | Binary or count | lme4::glmer() | Section 3 |
| Generalized estimating equations (GEE) | Continuous, binary or count | geepack::geeglm() | Sections 3 and 4 |
This section has established that dependence arises from the design of a study, that the ICC and the design effect measure its strength, and that ignoring it understates the uncertainty for cluster-level predictors. The narrated R walkthrough below demonstrates all of the methods in Table 5.3 on the lesson’s two datasets. Activity 5.1 then reproduces the main results of this section, from the ICC to the comparison in Table 5.2, before the knowledge check for the section.
Narrated R walkthrough: Mixed Models and GEE in R
This walkthrough uses the same two datasets as this lesson. It measures clustering with the intracluster correlation coefficient, fits and checks a linear mixed model, models a binary outcome with a generalized linear mixed model and with GEE, and analyses repeated measurements over time.
Open the Mixed Models and GEE in R walkthroughThis activity measures the clustering in the clinic data and compares an ordinary regression with a mixed model. Download phaa_clinics.csv and save it in the folder that holds your R script, then choose Session → Set Working Directory → To Source File Location in RStudio. The lesson uses the lme4, lmerTest and geepack packages, which can be installed once with the commented line at the top of the code.
# install.packages(c("lme4", "lmerTest", "geepack")) # run once, if not yet installed
library(lmerTest) # loads lme4 (for lmer()) and adds p-values
clinics <- read.csv("phaa_clinics.csv") # file must be in the working directory
clinics$clinic_id <- factor(clinics$clinic_id)
clinics$smoker <- factor(clinics$smoker, levels = c("No", "Yes"))
clinics$clinic_urban <- factor(clinics$clinic_urban, levels = c("rural", "urban"))
nlevels(clinics$clinic_id) # how many clinics?
summary(as.vector(table(clinics$clinic_id))) # patients per clinic
The factor() line tells R to treat clinic_id as a label for each clinic. The file holds 30 clinics with between 18 and 45 patients each (mean 32.2).
m0 <- lmer(sbp ~ 1 + (1 | clinic_id), data = clinics) # a model with clinics only
vc <- as.data.frame(VarCorr(m0))
vc[, c("grp", "vcov")] # variance between clinics and within clinics
icc <- vc$vcov[1] / sum(vc$vcov) # intracluster correlation coefficient
icc
The term (1 | clinic_id) asks for a separate baseline for each clinic. The variance between clinics is 22.10 and the variance within clinics (Residual) is 104.34, so the ICC is 22.10 ÷ 126.44 = 0.175.
m_bar <- mean(table(clinics$clinic_id)) # average clinic size
deff <- 1 + (m_bar - 1) * icc # design effect
deff
nrow(clinics) / deff # effective sample size
The design effect is 6.45, and the effective sample size is about 150 independent people.
naive <- lm(sbp ~ clinic_urban, data = clinics) # ignores clinics
mixed <- lmer(sbp ~ clinic_urban + (1 | clinic_id), data = clinics) # allows for clinics
summary(naive)$coefficients
summary(mixed)$coefficients
Reading the output. The first table is from lm(): urban clinics average 1.49 mmHg higher, with a standard error of 0.74 and a p-value of 0.044. The second table is from lmer(): the difference is 1.67 mmHg, but the standard error is 1.96 and the p-value is 0.40. The df column (about 27) reflects the 30 clinics, which are the real units of information for a clinic-level predictor.
R Reflect on what you just ran
Use the questions below to interpret the output you produced. Look at your console output before answering.
1. Report the ICC from m0 and explain in one sentence what it means for two patients who attend the same clinic.
2. Report the design effect and the effective sample size, and explain what the effective sample size tells you about the 966 patients.
3. Compare the estimate, standard error and p-value for clinic_urbanurban from naive and mixed. Which result would you report, and why?
clinic_urban is a clinic-level predictor with only 30 independent values, and the ordinary regression treats it as if it had 966. The ordinary regression understates the uncertainty, and the mixed model shows that the data cannot tell whether urban clinics differ from rural clinics.1. Which study produces repeated-measures data?
2. What usually happens to the standard error of a cluster-level predictor when clustering is ignored?
3. A dataset has a between-cluster variance of 5 and a within-cluster variance of 45. What is the ICC?
4. Clusters contain 21 people on average and the ICC is 0.05. What is the design effect?
5. In a study of patients in clinics, which variable is a cluster-level predictor?
✎ Reflection
This section explained that data are dependent when observations share a cluster, such as patients in a clinic or repeated visits by the same person. The intracluster correlation coefficient (ICC) is the share of the outcome's variation that lies between clusters, and the design effect, 1 + (average cluster size − 1) × ICC, shows how much information is lost; the effective sample size is the sample size divided by the design effect. Ignoring dependence makes standard errors too small, especially for cluster-level predictors that take one value per cluster. A health unit surveys 40 students in each of 25 schools (1,000 students in all) about their physical activity and wants to know whether schools with a daily physical education policy have more active students. The ICC for physical activity is 0.08. Calculate the design effect and the effective sample size, explain whether the school policy is a cluster-level or a person-level predictor, and describe what would go wrong if the analysis treated the 1,000 students as independent.
Linear Mixed Models
Introduction and Overview
This section presents the linear mixed model, the standard model for a continuous outcome when observations are clustered. It continues with systolic blood pressure in the 30 clinics of phaa_clinics.csv, now with four predictors: age, gender, smoking and whether the clinic is urban. The section explains the random intercept, shows how to read the fixed and random parts of the R output, lists the checks that a mixed model needs, and describes random slopes briefly.
Learning Objectives
- Describe a random intercept and explain how a linear mixed model differs from an ordinary linear regression.
- Fit a random-intercept model in R with
lmer()and interpret its fixed effects. - Interpret the random-effect variances and calculate the adjusted ICC.
- Check a linear mixed model with residual plots, a Q-Q plot of the cluster effects, the number of clusters and the singular-fit check.
- Explain what a random slope adds and when it is used.
The Random-Intercept Model
An ordinary linear regression has a single intercept. A random-intercept model gives each cluster its own intercept, made up of the overall intercept plus a cluster-specific shift. The shifts are treated as a random sample from a normal distribution with mean 0, and the model estimates the variance of that distribution, which describes how much the clusters differ (Laird & Ware, 1982). Equation 5.3 writes the model for systolic blood pressure in the clinic data.
The name "mixed" refers to the two kinds of effects in the model. The fixed effects (β0 to β4) are the coefficients for the predictors, read as differences in average blood pressure, as in Lesson 4. The random effects (uj) are the clinic shifts, summarised by their variance. Summarising the 30 clinics with one variance lets the model estimate the effect of a clinic-level predictor such as clinic_urban.
The three flip cards below restate the random intercept, the fixed effects and the variance components, with the lmer() notation for the random intercept.
With the parts of the model defined, the next part reads them from the R output for the clinic data.
Reading the Output
Activity 5.2 below fits the model with lmer() after loading the lmerTest package, which adds p-values to the fixed effects. The output has two main blocks. Table 5.4 summarises the fixed-effects block, with a 95% confidence interval and an interpretation for each predictor.
Table 5.4. Fixed effects from the random-intercept model for systolic blood pressure.
| Fixed effect | Estimate (mmHg) | 95% CI | p-value | Interpretation |
|---|---|---|---|---|
| Age (per year) | 0.41 | 0.37 to 0.45 | < 0.001 | Each extra year of age is associated with 0.41 mmHg higher blood pressure. |
| Female | −2.80 | −3.88 to −1.73 | < 0.001 | Women average 2.8 mmHg lower than men. |
| Smoker | 5.00 | 3.63 to 6.37 | < 0.001 | Smokers average 5.0 mmHg higher than non-smokers. |
| Urban clinic | 1.85 | −1.85 to 5.54 | 0.34 | There is no clear evidence of a difference between urban and rural clinics. |
Each estimate holds the other predictors constant. The df column of the output shows about 937 degrees of freedom for the patient-level predictors and about 28 for urban clinics, because the information about a clinic-level predictor comes from the 30 clinics.
The random effects block reports a clinic variance of 21.57 (standard deviation 4.64 mmHg) and a residual variance of 68.94 (standard deviation 8.30 mmHg). The adjusted ICC is 21.57 ÷ (21.57 + 68.94) = 0.24. It is larger than the ICC of 0.175 from the model with no predictors, because age, gender and smoking explain much of the variation among patients within clinics but little of the variation between clinics. Figure 5.4 shows the estimated shifts of the 30 clinic baselines, which the clinic variance summarises.

Worked Example 5.2 uses the intercept and the fixed effects of the model to predict blood pressure for two patients, and shows how a clinic shift such as those in Figure 5.4 changes the predictions.
Worked Example 5.2: Predicted Blood Pressure for Two Patients
For a 50-year-old male non-smoker in a rural clinic, the model predicts 90.01 + 0.408 × 50 = 110.4 mmHg in an average clinic. A 50-year-old male smoker in the same clinic is predicted to be 5.0 mmHg higher, at 115.4 mmHg. In a clinic whose estimated shift is +8 mmHg, both predictions rise by 8 mmHg, but the difference between them stays 5.0 mmHg, because the clinic shift is shared by everyone in the clinic.
These interpretations depend on the model being appropriate for the data, so the next part sets out the assumptions of a linear mixed model and how to check them.
Assumptions and How to Check Them
A linear mixed model makes the assumptions of linear regression, applied to the residuals within clusters, and adds assumptions about the clusters. Table 5.5 lists each assumption with what it means and how to check it, and Figure 5.5 shows the three diagnostic plots for the blood pressure model.
Table 5.5. Assumptions of a linear mixed model and how to check them.
| Assumption | What it means | How to check it |
|---|---|---|
| Linearity and equal variance | Each continuous predictor has a straight-line relationship with the outcome, and the residuals have the same spread at every fitted value. | Plot of residuals against fitted values. |
| Normal residuals | The differences among patients within a clinic are roughly normal. | Q-Q plot of the residuals. |
| Normal cluster effects | The clinic shifts come from a roughly normal distribution. | Q-Q plot of ranef(model). With few clusters this check is rough. |
| Enough clusters | The cluster variance is estimated from the clusters, so a reasonable number is needed. | nlevels(clinic_id); about 20 to 30 clusters is a common minimum. |
| Independent clusters | Clinics are unrelated to one another, and patients are independent within a clinic once the clinic effect is allowed for. | Judged from the study design. |
| Cluster variance estimated | The model is not singular, so the cluster variance is not estimated as zero. | isSingular(model) returns FALSE; a "boundary (singular) fit" message signals a problem. |

In this example the residual checks look acceptable, there are 30 clinics, and the model is not singular. With fewer than about 40 clusters, a small-sample correction to the tests is advised (Hemming & Taljaard, 2023), and the lmerTest output in this section already uses one (Satterthwaite's method). The three high clinics in panel C are a mild departure from normal cluster effects. Fixed-effect estimates are usually not very sensitive to this assumption, but the clinics themselves might be examined, for example to see whether they serve an older population or record blood pressure differently.
The checks support the random-intercept model for the clinic data. The final part of this section considers a more flexible model, in which the effect of a predictor may differ between clinics.
Random Slopes
The random-intercept model lets clinic baselines differ but assumes that each predictor has the same effect in every clinic. A random slope lets the effect of a predictor vary between clusters as well. In lmer(), a random slope for age is written (age | clinic_id), which gives each clinic its own intercept and its own age slope. Random slopes suit research questions about how an effect differs between settings, such as whether a program works better in some schools than others. They need more clusters and more observations per cluster, and with 30 clinics they often produce a singular fit or a convergence warning. This lesson fits random intercepts only.
This section has fitted a linear mixed model with a random intercept for each clinic, shown how to read its fixed effects, variance components and adjusted ICC, and checked it against the assumptions in Table 5.5. Activity 5.2 fits the same model in R and runs the checks, and the knowledge check that follows tests the main ideas of the section. Section 3 applies the same approach to a binary outcome.
This activity fits the linear mixed model and runs its checks. It loads the data again, so it can be run on its own.
library(lmerTest) # loads lme4 and adds p-values to lmer() output
clinics <- read.csv("phaa_clinics.csv") # file must be in the working directory
clinics$clinic_id <- factor(clinics$clinic_id)
clinics$smoker <- factor(clinics$smoker, levels = c("No", "Yes"))
clinics$clinic_urban <- factor(clinics$clinic_urban, levels = c("rural", "urban"))
lmm <- lmer(sbp ~ age + female + smoker + clinic_urban + (1 | clinic_id), data = clinics)
summary(lmm)
Reading the output. The first lines (the REML criterion and the scaled residuals) can be ignored for now. The Random effects block gives the clinic variance (21.57, standard deviation 4.644) and the residual variance among patients (68.94, standard deviation 8.303), and the line below it confirms 966 patients in 30 clinics. The Fixed effects block is read like a regression table: age 0.41 mmHg per year, women 2.80 mmHg lower, smokers 5.00 mmHg higher, and urban clinics 1.85 mmHg higher with p = 0.336. The Correlation of Fixed Effects block can be ignored for now.
confint(lmm, parm = "beta_", method = "Wald") # 95% CIs for the fixed effects
vc <- as.data.frame(VarCorr(lmm))
vc$vcov[1] / sum(vc$vcov) # ICC after adjusting for the predictors
The 95% confidence intervals agree with the p-values: only the interval for urban clinics (−1.85 to 5.54) includes 0. The adjusted ICC is 0.24. The intervals from method = "Wald" use the normal distribution, while the lmerTest p-values use a t distribution with the degrees of freedom shown, so for urban clinics the two can differ slightly.
par(mfrow = c(1, 3))
plot(fitted(lmm), resid(lmm), main = "Residuals vs fitted"); abline(h = 0, lty = 2)
qqnorm(resid(lmm), main = "Q-Q: residuals"); qqline(resid(lmm))
qqnorm(ranef(lmm)$clinic_id[, 1], main = "Q-Q: clinic effects"); qqline(ranef(lmm)$clinic_id[, 1])
par(mfrow = c(1, 1))
isSingular(lmm) # FALSE means the clinic variance was estimated without problems
The three plots match Figure 5.5 earlier in this section, and isSingular() returns FALSE, so the clinic variance was estimated without problems.
R Reflect on what you just ran
Use the questions below to interpret the output you produced. Look at your console output and plots before answering.
1. Report the fixed effect for smokerYes with its 95% confidence interval, and explain it in one sentence.
2. Use the random-effects block to calculate the adjusted ICC, and explain why it is larger than the ICC of 0.175 from the model with no predictors.
3. Describe what the three diagnostic plots and isSingular(lmm) show, and state whether the model is acceptable.
isSingular() returns FALSE, so the clinic variance was estimated. The model is acceptable, and the three high clinics are worth noting as a limitation and examining further.1. What does the term (1 | clinic_id) add to an lmer() model?
2. In a linear mixed model of blood pressure, the fixed effect for smoking is 5.0 mmHg. What does it mean?
3. A linear mixed model reports a clinic variance of 12 and a residual variance of 36. What is the ICC?
4. Which plot checks the assumption that the cluster effects are normally distributed?
ranef()) checks whether they follow a normal distribution.5. R reports "boundary (singular) fit" for a mixed model. What does this usually mean?
✎ Reflection
This section introduced the linear mixed model, which gives each cluster its own baseline (a random intercept, written (1 | clinic_id) in lmer()). Its fixed effects are read as differences in the average outcome, as in linear regression, and its random effects are summarised by a cluster variance and a residual variance, whose ratio gives the ICC. The model is checked with a residuals-versus-fitted plot, Q-Q plots of the residuals and of the cluster effects, the number of clusters (about 20 to 30 is a common minimum) and the singular-fit check. A researcher studies body mass index (BMI) among 1,200 employees in 15 workplaces, with age, gender and whether the workplace has an on-site cafeteria as predictors. Explain which terms you would include in an lmer() model and which of them are fixed or random, which predictor is at the workplace level, how you would interpret the cafeteria coefficient, and which assumption checks might be a concern with 15 workplaces.
lmer(bmi ~ age + female + cafeteria + (1 | workplace_id), data = ...). Age, gender and cafeteria are fixed effects, and (1 | workplace_id) is a random intercept that gives each workplace its own baseline BMI. The cafeteria variable is a workplace-level predictor, because it takes one value for every employee in a workplace, so its information comes from the 15 workplaces. Its coefficient would be the difference in average BMI between employees of workplaces with and without a cafeteria, holding age and gender constant, and its confidence interval would be wide because there are only 15 workplaces. With 15 workplaces, the number of clusters is below the usual minimum of about 20 to 30, so the workplace variance would be estimated imprecisely and the model could be singular, and the Q-Q plot of 15 workplace effects would be hard to judge. I would still check the residual plots, report the number of workplaces as a limitation and consider whether more workplaces could be recruited.Binary Outcomes: Mixed Models and GEE
Introduction and Overview
This section extends logistic regression to clustered data. The outcome is referred, which records whether each of the 966 patients in phaa_clinics.csv was referred to a specialist (246 were, or 25.5%). The predictors are age, smoking and urban clinic. The section fits a generalized linear mixed model (GLMM) and a generalized estimating equations (GEE) model, compares them with an ordinary logistic regression, and explains when each approach is preferred.
Learning Objectives
- Fit a logistic GLMM with
glmer()and a logistic GEE model withgeeglm()in R. - Interpret odds ratios from both models and compare their standard errors with an ordinary logistic regression.
- Distinguish clinic-specific (conditional) from population-averaged (marginal) odds ratios in plain language.
- Choose between a GLMM and GEE using the research question and the number of clusters.
- List the checks for each approach.
Two Ways to Allow for Clustering
Logistic regression can allow for clustering in two ways, which correspond to the two families of methods introduced in Section 1 and listed in Table 5.3. A GLMM gives each clinic its own baseline log-odds, and GEE fits one model for the whole population and calculates standard errors that allow for the clustering. The two subsections below describe each approach in turn.
The Generalized Linear Mixed Model
A generalized linear mixed model (GLMM) adds random effects to a generalized linear model. For a binary outcome, it is a logistic regression in which each clinic has its own baseline log-odds, with the clinic shifts drawn from a normal distribution. It is fitted with glmer() from lme4, which takes the same family = binomial argument as glm(). Equation 5.4 writes the GLMM for referral in the clinic data.
Generalized Estimating Equations
Generalized estimating equations (GEE) fit a logistic regression without clinic effects. A working correlation describes how alike patients in the same clinic are assumed to be, and GEE uses it to weight the data. The standard errors are then calculated from the variation between clinics, which allows for the clustering (Zeger & Liang, 1986). The analyst chooses the working correlation structure. For people in clinics, schools or households, the usual choice is "exchangeable", which assumes that any two members of a cluster are equally correlated. The corrected (sandwich) standard errors remain valid even if the working correlation is not exactly right, provided there are enough clusters. GEE is fitted with geeglm() from geepack, which needs the cluster identifier in the id argument and the data sorted so that each cluster's rows are together.
The three flip cards below define terms that recur in the rest of this section: the clinic-specific odds ratio that a GLMM estimates, the population-averaged odds ratio that GEE estimates, and the working correlation that GEE uses.
The two approaches therefore estimate different quantities: the GLMM gives clinic-specific odds ratios and GEE gives population-averaged odds ratios. The next part fits both models to the referral data and compares their results with an ordinary logistic regression.
Comparing the Results
Activity 5.3 below fits an ordinary logistic regression (glm()), a GLMM (glmer()) and GEE (geeglm()) with the same three predictors. Table 5.6 shows the odds ratios for smoking (a patient-level predictor) and urban clinic (a clinic-level predictor), with their standard errors on the log-odds scale.
Table 5.6. Odds ratios for smoking and urban clinic, with standard errors on the log-odds scale, from three models of specialist referral.
| Model | OR for smoking | SE (smoking) | OR for urban clinic | SE (urban clinic) |
|---|---|---|---|---|
Ordinary logistic regression, glm() | 1.72 | 0.188 | 2.16 | 0.168 |
GLMM, glmer() | 1.67 | 0.194 | 2.31 | 0.279 |
GEE, geeglm() | 1.64 | 0.186 | 2.04 | 0.289 |
Figure 5.6 plots the same odds ratios with their 95% confidence intervals.

For smoking, the three models give similar odds ratios and standard errors, because smokers and non-smokers are found in every clinic and the comparison can be made within clinics. For urban clinic, the standard error rises from 0.168 in the ordinary logistic regression to 0.279 in the GLMM and 0.289 in GEE, an increase of about 70%. The odds ratio remains clearly above 1 in all three models: patients in urban clinics have about twice the odds of referral of patients in rural clinics of the same age and smoking status (GLMM OR 2.31, p = 0.003; GEE OR 2.04, p = 0.014).
The GEE odds ratio for urban clinics (2.04) is a little lower than the glm() odds ratio (2.16) because the exchangeable working correlation gives each patient in a large clinic slightly less weight. Refitting GEE with corstr = "independence" reproduces the glm() odds ratio of 2.16, with the corrected standard error of 0.289.
Worked Example 5.3 explains why the GLMM odds ratio for urban clinics in Table 5.6 is further from 1 than the GEE odds ratio.
Worked Example 5.3: Why the GLMM Odds Ratio Is Further From 1
Suppose that a patient in an urban clinic has 2.3 times the odds of referral of a similar patient in a rural clinic with the same baseline. Clinics also differ in their baseline odds, so the population of urban patients mixes clinics with high and low baselines, and so does the population of rural patients. Averaging the probability of referral over this mix pulls the population comparison toward 1, so the population-averaged odds ratio is smaller than the clinic-specific odds ratio. Averaging over clinics is one reason the GEE odds ratio (2.04 here) is smaller than the GLMM odds ratio (2.31), and the weighting used by GEE and chance variation also contribute in this sample. The larger the variation between clinics, the larger the gap. For a continuous outcome with an identity link, averaging does not change the difference, so the two kinds of estimate are the same.
The GLMM and GEE agree that urban clinics have about twice the odds of referral, and the validity of each result rests on assumptions that the next part sets out.
Assumptions and How to Check Them
The GLMM and GEE share some assumptions and differ in others, including the number of clusters each needs. Table 5.7 lists the assumptions of each approach with how to check them, and Box 5.2 describes a step that GEE requires before the model is fitted.
Table 5.7. Assumptions of the logistic GLMM and GEE, with how to check them.
| Assumption | GLMM | GEE | How to check it |
|---|---|---|---|
| Binary outcome with enough events | Required | Required | table(outcome); about 10 events per predictor (246 events here). |
| Independent clusters | Required | Required | Judged from the study design. |
| Enough clusters | About 20 to 30 | About 30 to 40 or more | nlevels(clinic_id); 30 clinics here, at the lower limit for GEE. |
| Normal cluster effects (log-odds scale) | Assumed | Not assumed | Q-Q plot of ranef(model). |
| Model fitted without problems | Read any convergence warnings | Correct id, data sorted by cluster | Warnings in the console; the "Number of clusters" line in the GEE output. |
⚠ Box 5.2: Sort the data before using geeglm()
geeglm() treats consecutive rows with the same id as one cluster. If the rows of a clinic are scattered through the file, the function splits that clinic into several clusters and the standard errors are wrong without any warning. Sorting the data by the cluster identifier (and by time for repeated measures) before fitting avoids the problem. The line Number of clusters: 30 in the output confirms that the clinics were read correctly.
With 30 clinics, the referral data meet the GLMM requirement for the number of clusters and sit at the lower limit for GEE. The checks alone therefore leave the choice between the two models open, and the next part turns to the research question.
Choosing Between a GLMM and GEE
The choice depends mainly on the research question (Subramanian & O'Malley, 2010). A GLMM suits questions about individual clusters, estimates how much the clusters vary, and works with fewer clusters. GEE suits questions about the population as a whole, makes no assumption about the distribution of cluster effects, and needs more clusters for reliable standard errors (Hubbard et al., 2010). In practice, many epidemiological papers report one approach as the main analysis and the other as a sensitivity analysis. When they agree, as they do for urban clinics here, the conclusion is stronger.
This section has fitted a GLMM and GEE to a binary outcome and shown that both widen the standard error for the clinic-level predictor while reaching the same conclusion for urban clinics. Activity 5.3 fits the three models in Table 5.6 in R and compares them, and the knowledge check that follows tests the main ideas of the section. Section 4 applies a linear mixed model and GEE to repeated measurements of the same people.
This activity fits an ordinary logistic regression, a GLMM and a GEE model to the referral outcome and compares them.
library(lme4); library(geepack) # glmer() for the GLMM, geeglm() for GEE
clinics <- read.csv("phaa_clinics.csv") # file must be in the working directory
clinics$clinic_id <- factor(clinics$clinic_id)
clinics$smoker <- factor(clinics$smoker, levels = c("No", "Yes"))
clinics$clinic_urban <- factor(clinics$clinic_urban, levels = c("rural", "urban"))
table(clinics$referred) # 1 = referred to a specialist
naive <- glm(referred ~ age + smoker + clinic_urban, family = binomial, data = clinics)
glmm <- glmer(referred ~ age + smoker + clinic_urban + (1 | clinic_id),
family = binomial, data = clinics)
summary(glmm)
Reading the output. The table shows 246 referrals among 966 patients. In the GLMM, the Random effects block gives a clinic variance of 0.30 on the log-odds scale (standard deviation 0.55), and the Fixed effects block is read like a logistic regression: each coefficient is a log odds ratio for patients in the same clinic or, for urban clinic, in clinics with the same baseline. The urban-clinic coefficient is 0.836 (SE 0.279, p = 0.003), which is an odds ratio of e0.836 = 2.31.
clinics <- clinics[order(clinics$clinic_id), ] # GEE needs each clinic's rows together
gee <- geeglm(referred ~ age + smoker + clinic_urban, id = clinic_id,
family = binomial, corstr = "exchangeable", data = clinics)
summary(gee)
options(digits = 7) # summary() of a GEE model lowers the printed digits; this restores the default
The GEE output gives population-averaged coefficients with corrected (sandwich) standard errors in the Std.err column and Wald tests in the next two columns. The urban-clinic coefficient is 0.711 (SE 0.289, p = 0.014), an odds ratio of 2.04. The estimated exchangeable correlation (alpha) is 0.04, and the output confirms 30 clusters. The Estimated Scale Parameters block can be ignored.
# Odds ratios and standard errors for urban clinics from the three models
se <- function(fit) summary(fit)$coefficients["clinic_urbanurban", 2]
b <- c(naive = coef(naive)[["clinic_urbanurban"]], glmm = fixef(glmm)[["clinic_urbanurban"]],
gee = coef(gee)[["clinic_urbanurban"]])
round(cbind(OR = exp(b), SE = c(se(naive), se(glmm), se(gee))), 3)
The comparison table shows that the odds ratio for urban clinics is about 2 in all three models, while its standard error rises from 0.168 when clinics are ignored to 0.279 (GLMM) and 0.289 (GEE).
R Reflect on what you just ran
Use the questions below to interpret the output you produced. Look at your console output before answering.
1. Report the odds ratio for urban clinics from the GLMM and from GEE, and explain the difference between what the two odds ratios describe.
2. Compare the standard errors for clinic_urbanurban and for smokerYes across the three models, and explain why one changes much more than the other.
3. A provincial planner asks whether patients of urban clinics are more likely to be referred across the province. Which model's result would you give, and what check would you mention about it?
1. Which R function fits a logistic regression with a random intercept for each clinic?
glmer() from lme4 fits generalized linear mixed models; with family = binomial and a term such as (1 | clinic_id) it is a logistic regression with a random intercept.2. What does GEE do to account for clustering?
3. A GLMM gives an odds ratio of 2.3 and GEE gives 2.0 for the same predictor. What is the most likely explanation?
4. Why do GEE standard errors need a reasonably large number of clusters?
5. Which working correlation does this lesson use for patients clustered in clinics?
✎ Reflection
This section compared two ways of allowing for clustering with a binary outcome. A generalized linear mixed model (GLMM, fitted with glmer()) adds a random intercept for each cluster to a logistic regression and gives clinic-specific (conditional) odds ratios. Generalized estimating equations (GEE, fitted with geeglm()) fit a logistic regression with no cluster effects, calculate standard errors that allow for the correlation within clusters, and give population-averaged (marginal) odds ratios; they need more clusters, about 30 to 40 or more, and data sorted by cluster. Both methods widen the standard errors of cluster-level predictors compared with an ordinary logistic regression. A research team studies whether a smoking-cessation counselling program offered by some pharmacies is associated with quitting, using records of 2,400 customers from 60 pharmacies (30 with the program and 30 without). The team wants to tell the provincial health ministry how quit rates would differ if every pharmacy offered the program. Explain which method you would use as the main analysis and why, what the program variable is (cluster level or person level), what an ordinary logistic regression would get wrong, and which other method you would report as a sensitivity analysis.
geeglm(quit ~ program + age + ..., id = pharmacy_id, family = binomial, corstr = "exchangeable"), with the data sorted by pharmacy. With 60 pharmacies there are enough clusters for the corrected standard errors. An ordinary logistic regression would treat the 2,400 customers as independent and would give a standard error for the program that is too small, so the confidence interval would be too narrow and the program could look effective when the evidence is weak. A GLMM with a random intercept for pharmacy would be a useful sensitivity analysis; its odds ratio would be pharmacy-specific (cluster-specific) and probably a little further from 1, and it would also show how much quit rates vary between pharmacies.Repeated Measures Over Time
Introduction and Overview
This section applies the methods of the lesson to repeated measures, in which the same people are measured at several times. The example is phaa_repeated.csv, a simulated wellness trial in which 200 adults were assigned to a control arm or an intervention arm (100 each) and were due to attend visits at 0, 6, 12 and 18 months. At each visit the study recorded systolic blood pressure (sbp_mmhg) and whether the person was adhering to the program (adherent = 1). The section covers the layout of repeated-measures data, missed visits, a linear mixed model for the change in blood pressure, and GEE for the repeated binary outcome.
Learning Objectives
- Recognise repeated-measures data and explain why each person is a cluster of observations.
- Distinguish long from wide format and identify the variables a repeated-measures model needs.
- Explain how a mixed model handles missed visits and what the missing-at-random condition means.
- Fit and interpret a linear mixed model with an interaction between study arm and time.
- Fit and interpret a GEE model for a repeated binary outcome, and list the checks for repeated-measures analyses.
Repeated Measures as Clustered Data
When the same person is measured more than once, the measurements share that person's genes, habits, circumstances and baseline health, so they are more alike than measurements from different people. Each person is therefore a cluster of visits, and the methods from the earlier sections apply with the person in place of the clinic. In this trial, the ICC for blood pressure is 0.56: more than half of the variation is a stable difference between people, much more than the clustering of patients in clinics.
The two subsections below describe how the trial data are laid out for these methods and what a plot of the data shows about the dependence.
Long and Wide Format
Repeated-measures data can be stored in wide format, with one row per person and a column for each visit, or in long format, with one row per visit and columns for the person identifier, the visit time and the outcome. Mixed models and GEE in R need long format. The trial file is already in long format, with 800 rows (200 people × 4 visits). Table 5.8 shows the first five rows of the file.
Table 5.8. The first five rows of phaa_repeated.csv in long format, with one row per visit.
| id | arm | visit (months) | sbp_mmhg | adherent |
|---|---|---|---|---|
| R0001 | control | 0 | 132 | 0 |
| R0001 | control | 6 | 131 | 0 |
| R0001 | control | 12 | 141 | 0 |
| R0001 | control | 18 | 126 | 0 |
| R0002 | control | 0 | 127 | 1 |
The id column identifies the person (the cluster), visit records months since the start, and each person appears once for each visit. In wide format, the same person R0001 would be a single row with columns such as sbp_0, sbp_6, sbp_12 and sbp_18. The base R function reshape() or tidyr::pivot_longer() converts wide data to long format.
Looking at the Data
Before any model is fitted, a plot of the measurements over time shows how strongly each person’s visits are linked and what shape the trend takes. Figure 5.7 shows the blood pressure of individual participants at each visit and the average in each arm.

The spaghetti plot (panel A) shows the dependence directly: people start at very different levels and tend to stay there. The averages (panel B) fall in both arms, from 130.4 to 127.0 mmHg in the control arm and from 128.9 to 123.1 mmHg in the intervention arm, and the roughly straight lines suggest that a linear trend over time is reasonable.
The trial data are therefore in the long format that the models need, and Figure 5.7 shows both the dependence within people and a roughly linear trend. Some planned visits were missed, however, and the next part considers how missed visits affect the analysis.
Missed Visits
Of the 800 planned measurements of blood pressure, 96 (12%) are missing, and only 121 of the 200 participants attended all four visits. Dropping everyone with a missed visit (a complete-case analysis) would discard 79 people and could bias the results if the people who missed visits differ from those who attended every one. For a regression model, a complete-case analysis still gives unbiased coefficients when the chance that a record is incomplete depends only on the predictors in the model and not on the outcome, although it loses precision; this exception refines the statement in Lesson 2 that listwise deletion is biased unless the data are MCAR. In repeated-measures data a missed visit often depends on the person’s earlier outcome values, and then the exception does not apply. A mixed model uses every measurement that was taken, here 704 measurements from all 200 people.
Box 5.3 recalls the three missing-data mechanisms from Lesson 2 and ends with a retrieval question, and Box 5.4 restates the missing-at-random condition in plain terms for the trial.
Box 5.3: Recall: Lesson 2, Section 1 (Missing Data)
Lesson 2, Section 1 set out Rubin’s three missing-data mechanisms. Data are missing completely at random (MCAR) when the chance that a value is missing is unrelated to any value, observed or not. They are missing at random (MAR) when that chance depends only on values that were observed, and missing not at random (MNAR) when it depends on the missing value itself. Students who took HSCI 230 first met these mechanisms in Lesson 8, Section 2 (Attrition and Nonresponse Bias) and Lesson 11, Section 2 (Statistical Inference and Model Issues).
Retrieval question. A participant in the wellness trial misses the 12-month visit. Give one reason for the missed visit that would make the missing blood pressure MAR, and one that would make it MNAR.
Box 5.4: Missing at random, in plain terms
A mixed model fitted to all available visits gives valid results when the chance of missing a visit depends only on information the model already uses, such as the person's arm or their blood pressure at earlier visits. This condition is called missing at random (MAR). It would fail if, for example, people stayed away from a visit because their blood pressure was high on that day, in a way the earlier visits could not predict. MAR cannot be proved from the data, but it is a much weaker assumption than the complete-case assumption that people who attended every visit are typical of everyone. Comparing people who missed visits with those who did not at their first visit shows which measured characteristics predict a missed visit, so that they can be included in the model. The comparison cannot confirm MAR, because MAR concerns the values that were never recorded.
When the missing-at-random condition holds, a mixed model fitted to all 704 available measurements gives valid results. The next part fits that model to the blood pressure data.
A Mixed Model for Change Over Time
The model for blood pressure includes a random intercept for each person and fixed effects for arm, visit and their interaction. Equation 5.5 writes the model.
Table 5.9 gives the estimates of the fixed effects for arm, visit and their interaction, with an interpretation of each.
Table 5.9. Fixed effects from the random-intercept model for blood pressure over time.
| Term | Estimate | SE | p-value | Interpretation |
|---|---|---|---|---|
| Intervention arm (month 0) | −1.32 mmHg | 1.07 | 0.22 | The arms start at similar levels, as expected after randomization. |
| Visit (control arm, per month) | −0.160 mmHg | 0.043 | < 0.001 | Blood pressure falls by about 0.16 mmHg per month in the control arm. |
| Arm × visit (per month) | −0.149 mmHg | 0.061 | 0.014 | Blood pressure falls an extra 0.15 mmHg per month in the intervention arm. |
Over the 18 months of the trial, the extra fall in the intervention arm is 18 × −0.149 = −2.7 mmHg. The random effects give a between-person variance of 34.80 and a within-person variance of 27.58, so the ICC is 34.80 ÷ (34.80 + 27.58) = 0.56.
Worked Example 5.4 combines the intercept of the model with the estimates in Table 5.9 to predict blood pressure at month 18 in each arm.
Worked Example 5.4: Predicted Blood Pressure at Month 18
For a typical person in the control arm, the model predicts 130.02 − 0.160 × 18 = 127.1 mmHg at month 18. For a typical person in the intervention arm, it predicts 130.02 − 1.32 + (−0.160 − 0.149) × 18 = 123.1 mmHg. Both predictions are close to the observed averages of 127.0 and 123.1 mmHg.
The accordion below describes two extensions of this model, random slopes for time and a correlation that depends on the time between visits, both of which are beyond the scope of this lesson.
The random-intercept model gives each person their own level but the same slope over time within each arm. A random slope, (visit | id), would let each person have their own rate of change. In this trial that model produces a convergence warning, because four visits per person give little information about individual slopes. Visits close together in time are also often more alike than visits far apart, a pattern that models with an autoregressive correlation structure (such as AR(1)) describe. Both extensions appear in published longitudinal studies and are beyond the scope of this lesson.
The mixed model shows an extra fall of about 2.7 mmHg over 18 months in the intervention arm. The trial also recorded a binary outcome at each visit, and the next part models it with GEE.
GEE for a Repeated Binary Outcome
Adherence is recorded as yes or no at each visit. The share adherent falls slightly in the control arm (0.43 at month 0 to 0.37 at month 18) and rises steadily in the intervention arm (0.42 to 0.73). Figure 5.8 shows these proportions at each visit.

A GEE model with the person as the cluster gives population-averaged odds ratios for the trial, which matches the question of how the program changes adherence across participants. With 200 people there are plenty of clusters for the corrected standard errors. Table 5.10 gives the odds ratios from this model.
Table 5.10. Odds ratios from the GEE model for adherence over time.
| Term | Odds ratio | 95% CI | Interpretation |
|---|---|---|---|
| Intervention arm (month 0) | 1.00 | 0.60 to 1.69 | The arms start with the same odds of adherence. |
| Visit (control arm, per month) | 0.99 | 0.96 to 1.02 | Adherence in the control arm barely changes. |
| Arm × visit (per month) | 1.093 | 1.041 to 1.147 | The monthly odds ratio is 0.99 × 1.093 = 1.08 in the intervention arm, a rise of about 8% per month. |
Over one six-month interval between visits, the interaction corresponds to an odds ratio of 1.0936 ≈ 1.70. The estimated exchangeable correlation between a person's visits is 0.07, much weaker than the correlation for blood pressure, but GEE allows for it in the standard errors.
GEE needs a stronger condition about missed visits than the mixed model. Its results are valid when the chance of missing a visit depends only on the predictors in the GEE model, here arm and visit. If missed visits depend on earlier outcomes, such as earlier blood pressure or adherence, a mixed model, or a weighted form of GEE that is beyond this lesson, is preferred.
GEE therefore shows a steady rise in adherence in the intervention arm, provided that missed visits depend only on arm and visit. The next part collects the checks that apply to both repeated-measures models.
Assumptions and How to Check Them
A repeated-measures analysis needs some of the checks from the earlier sections together with checks of its own, which concern the layout of the data, the coding of time and the missed visits. Table 5.11 lists them for the mixed model and for GEE.
Table 5.11. Assumptions and requirements of a repeated-measures analysis, with how to check them.
| Assumption or requirement | How to check it |
|---|---|
| Data in long format with a person identifier | head(data); for GEE, sort by id and then by visit. |
| Time coded correctly and the trend shape reasonable | Plot the averages by visit; roughly straight lines support a linear trend in visit. |
| Residual assumptions for the mixed model | Residuals versus fitted values and Q-Q plots, as in Section 2. |
| Missed visits: missing at random for the mixed model; related only to the model's predictors for GEE | Count missing values by visit and compare people who missed visits with those who did not. This shows which variables to include; it cannot confirm MAR. |
| Enough clusters for GEE | The Number of clusters line of the output (200 here). |
| Independent people | Judged from the study design (one person per household, for example). |
These checks complete the analysis of the wellness trial. The final part sets the four examples of the lesson side by side.
Bringing the Lesson Together
The four sections of this lesson apply one approach. The cluster variable is identified first, the clustering is measured with the ICC, and a model is chosen that allows for it: a linear mixed model for a continuous outcome, a GLMM or GEE for a binary outcome, and the same models with the person as the cluster for repeated measures. Table 5.12 summarises the four examples with the cluster, the model and R function, and the main result of each.
Table 5.12. The four examples of the lesson, with the cluster, model and main result of each.
| Example | Cluster | Model and R function | Main result |
|---|---|---|---|
| Blood pressure in clinics | Clinic | Linear mixed model, lmer() | Urban minus rural 1.85 mmHg (−1.85 to 5.54); ICC 0.24 |
| Referral in clinics | Clinic | GLMM, glmer(), and GEE, geeglm() | Urban OR 2.31 (GLMM) and 2.04 (GEE) |
| Blood pressure over time | Person | Linear mixed model, lmer() | Extra fall of 0.149 mmHg per month in the intervention arm |
| Adherence over time | Person | GEE, geeglm() | Interaction OR 1.093 per month (1.041 to 1.147) |
Activity 5.4 fits the mixed model for blood pressure over time in R, and Activity 5.5 continues from it with the GEE model for adherence. The knowledge check that follows the two activities tests the main ideas of this section, and the final page of the lesson gathers the key takeaways and the final assessment.
This activity fits the linear mixed model for blood pressure in the wellness trial. Download phaa_repeated.csv and save it in your working directory. The next activity continues from this one.
library(lmerTest) # loads lme4 and adds p-values
visits <- read.csv("phaa_repeated.csv") # file must be in the working directory
visits$id <- factor(visits$id)
visits$arm <- factor(visits$arm, levels = c("control", "intervention"))
head(visits, 8) # long format: one row per visit
table(visit = visits$visit, missing = is.na(visits$sbp_mmhg))
round(tapply(visits$sbp_mmhg, list(visits$arm, visits$visit), mean, na.rm = TRUE), 1)
The first eight rows show the long format: person R0001 has four rows, one per visit, followed by person R0002. The table of missing values shows between 20 and 32 missed measurements at each visit (96 in all), and the averages by arm and visit match Figure 5.7.
lmm_t <- lmer(sbp_mmhg ~ arm * visit + (1 | id), data = visits)
summary(lmm_t)
Reading the output. The line Number of obs: 704, groups: id, 200 confirms that the model used all 704 available measurements from all 200 people. In the Fixed effects block, armintervention (−1.32, p = 0.22) is the difference between the arms at month 0, visit (−0.160, p < 0.001) is the change per month in the control arm, and armintervention:visit (−0.149, p = 0.014) is the extra change per month in the intervention arm.
vc <- as.data.frame(VarCorr(lmm_t))
vc$vcov[1] / sum(vc$vcov) # how alike one person's visits are
18 * fixef(lmm_t)[["armintervention:visit"]] # extra change over 18 months
The ICC of 0.56 shows that a person's visits are strongly alike, and the extra fall in blood pressure in the intervention arm over 18 months is 2.7 mmHg.
R Reflect on what you just ran
Use the questions below to interpret the output you produced. Look at your console output before answering.
1. Report the estimate, standard error and p-value for armintervention:visit, and explain in one or two sentences what it says about the program.
2. How many measurements did the model use, and why is this better than analysing only the 121 people who attended all four visits? What condition must hold for the result to be valid?
3. Report the ICC from lmm_t and compare it with the ICC for patients in clinics (0.175). What does the difference mean?
This activity continues from the previous one and uses the visits data frame created there. It fits a GEE model for the repeated binary outcome, adherence.
library(geepack)
adh <- visits[!is.na(visits$adherent), ] # visits with adherence recorded
adh <- adh[order(adh$id, adh$visit), ] # each person's rows together
round(tapply(adh$adherent, list(adh$arm, adh$visit), mean), 2) # share adherent
gee_a <- geeglm(adherent ~ arm * visit, id = id, family = binomial,
corstr = "exchangeable", data = adh)
summary(gee_a)
options(digits = 7) # restore the default number of printed digits
Reading the output. The table of shares adherent matches Figure 5.8. In the GEE output, armintervention (0.005) shows no difference between the arms at month 0, visit (−0.012) shows little change in the control arm, and armintervention:visit (0.089, p < 0.001) shows that adherence rises faster in the intervention arm. The estimated correlation between a person's visits (alpha) is 0.07, and there are 200 clusters.
round(exp(cbind(OR = coef(gee_a), confint.default(gee_a))), 3) # odds ratios, 95% CIs
The odds ratio for the interaction is 1.093 per month (95% CI 1.041 to 1.147). The function confint.default() gives Wald confidence intervals from the corrected standard errors.
R Reflect on what you just ran
Use the questions below to interpret the output you produced. Look at your console output before answering.
1. Report the odds ratio and 95% confidence interval for armintervention:visit, and explain what it means for adherence in the two arms.
2. Why is GEE, with id = id, a reasonable choice for this outcome, and why must the data be sorted before fitting it?
geeglm() treats consecutive rows with the same id as one cluster, so the rows must be sorted by person (and by visit) or a person's visits could be split into several clusters, giving wrong standard errors.3. The estimated correlation (alpha) between a person's adherence measurements is 0.07, while the ICC for blood pressure was 0.56. Would it be acceptable to analyse adherence with an ordinary glm() because the correlation is small? Explain.
glm() result as a comparison, is the appropriate approach.1. In repeated-measures data, what is the cluster?
2. Which data layout do lmer() and geeglm() need for repeated measures?
3. In the model lmer(sbp_mmhg ~ arm * visit + (1 | id)), which term tests whether blood pressure changes at a different rate in the two arms?
4. Why can a mixed model use people who missed some visits?
5. A GEE interaction odds ratio is 1.093 per month. What is the corresponding odds ratio over a six-month interval?
✎ Reflection
This section treated repeated measures as clustered data in which each person is a cluster of visits. The data must be in long format (one row per visit) with a person identifier. A linear mixed model such as lmer(outcome ~ arm * visit + (1 | id)) gives each person a random intercept, its arm:visit interaction tests whether the outcome changes at a different rate in the two arms, and it uses every visit that was attended, which is valid if missed visits are missing at random (missingness depends only on information in the model). GEE with id as the cluster gives population-averaged odds ratios for a repeated binary outcome. A study follows 300 older adults, half of whom join a weekly walking group, and records their walking speed (in metres per second) and whether they had a fall in the previous three months, every three months for one year (five visits). About 15% of visits are missed, more often among people who were frailer at their first visit. Describe the data layout you would need, the model you would fit for walking speed and the term that answers the main question, the model you would fit for falls, and what the pattern of missed visits means for the analysis.
lmer(speed ~ group * month + frailty + (1 | id)), which gives each person their own baseline speed; the group:month interaction answers the main question, whether walking speed changes at a different rate in the walking group, and I would check the residual plots and whether the average speeds by visit look roughly linear. For falls, a repeated binary outcome, I would fit GEE with geeglm(fall ~ group * month + frailty, id = id, family = binomial, corstr = "exchangeable") after sorting the data by person and visit; with 300 people there are plenty of clusters, and the interaction odds ratio would describe how the odds of a fall change over time in the walking group compared with the other group. Because frailer people at the first visit miss more visits, a complete-case analysis would keep a healthier group and could bias the results, while the mixed model uses all visits and is valid if missingness depends on observed information such as baseline frailty, so I would include baseline frailty in the models (the first-visit walking speed is already part of the outcome data that the mixed model uses) and compare people who missed visits with those who did not. For the GEE model of falls, baseline frailty also needs to be a predictor, because GEE is valid only when missed visits depend on the predictors in the model.Lesson 5: Final Assessment
Bringing It All Together
This lesson addressed the assumption of independence that every model in the previous lessons shares. Section 1 showed that observations are dependent when they share a cluster, such as patients in the same clinic or visits by the same person. The intracluster correlation coefficient measured the clustering in the clinic data (0.175 for systolic blood pressure), the design effect of 6.45 showed that the 966 patients carried about as much information as 150 independent patients, and an ordinary regression that ignored the clinics gave a standard error for urban clinics of 0.74 mmHg, compared with 1.96 mmHg from a model that allowed for them.
Section 2 fitted a linear mixed model with a random intercept for each clinic using lmer(). Its fixed effects were read like the coefficients of a linear regression, its random effects gave a clinic variance and a residual variance whose ratio was the adjusted ICC of 0.24, and it was checked with residual plots, a Q-Q plot of the clinic effects, the number of clinics and a test for a singular fit. Section 3 turned to a binary outcome, specialist referral, and compared a logistic mixed model fitted with glmer(), which gives cluster-specific odds ratios, with GEE fitted with geeglm(), which gives population-averaged odds ratios with sandwich standard errors. Section 4 treated each person in a wellness trial as a cluster of visits, arranged the data in long format, and used a mixed model for blood pressure and GEE for adherence, each with an arm-by-visit interaction that answered the main question of the trial and each using every visit that was attended.
Across the lesson, the same steps were followed each time: the cluster variable was identified, the clustering was measured, a model that allows for it was chosen to suit the outcome type and the research question, and the model's assumptions were checked before the results were reported. The final assessment asks for these steps to be applied to new studies.
Key Takeaways from this lesson
- Observations are dependent when they share a cluster, and the cluster variable (clinic, school, neighbourhood or person) is identified from the study design before any model is fitted.
- The ICC is the share of the outcome's variation that lies between clusters, and the design effect, 1 + (average cluster size − 1) × ICC, shows how much information the clustering removes.
- Ignoring clustering usually makes standard errors too small, and the problem is largest for cluster-level predictors such as an urban clinic or a school-wide program; for person-level predictors, allowing for clustering changes the standard error little and can make it smaller.
- A linear mixed model with a random intercept,
lmer(y ~ x + (1 | cluster)), gives each cluster its own baseline, and its fixed effects are read like ordinary regression coefficients. - A mixed model is checked with residual plots, a Q-Q plot of the cluster effects, enough clusters (about 20 to 30 or more) and a test for a singular fit.
- For a binary outcome, a GLMM (
glmer()) gives cluster-specific odds ratios and GEE (geeglm()) gives population-averaged odds ratios, which are usually a little closer to 1. - Repeated measures are analysed in long format, the group-by-time interaction tests whether the groups change at different rates, and a mixed model that uses every attended visit is valid when missed visits are missing at random.
The final assessment covers all four sections. All 15 questions must be answered correctly (100%), and the final reflection completed, to finish the lesson.
Reflection
A study evaluates a school-based physical activity program in 40 elementary schools, 20 of which were randomly assigned to run the program. About 50 students are surveyed in each school (2,000 students in all). The outcomes are the minutes of physical activity each student reports per day and whether the student meets the guideline of 60 minutes per day (yes or no). The predictors are the program (a school-level variable), the student's age and gender. A model with no predictors gives an ICC of 0.04 for minutes of activity. This lesson showed that observations in the same cluster are dependent, that the design effect is 1 + (average cluster size − 1) × ICC and the effective sample size is the sample size divided by the design effect, that a linear mixed model with a random intercept is fitted with lmer(y ~ x + (1 | cluster)) and checked with residual plots, a Q-Q plot of the cluster effects, the number of clusters and isSingular(), and that a binary outcome can be modelled with a GLMM (glmer(), cluster-specific odds ratios) or GEE (geeglm(), population-averaged odds ratios). Identify the cluster, calculate the design effect and the effective sample size, and explain what would happen to the standard error for the program if the schools were ignored. Then state the model and R code you would use for each outcome, what the program coefficient or odds ratio would mean, and the main checks you would carry out.
lmer(minutes ~ program + age + gender + (1 | school_id), data = students) after loading lmerTest. The program coefficient would be the difference in average minutes of activity between students of the same age and gender in program and non-program schools; for example, a coefficient of 8 would mean about 8 more minutes per day. I would check the residuals versus fitted values and the Q-Q plot of the residuals, a Q-Q plot of the school effects from ranef(), that 40 schools is enough (it is above the rough minimum of 20 to 30), and that isSingular() is FALSE. For meeting the guideline, a binary outcome, I would fit either a GLMM, glmer(meets ~ program + age + gender + (1 | school_id), family = binomial), whose odds ratio compares a student in a program school with a student of the same age and gender in a non-program school with the same baseline, or GEE, geeglm(meets ~ program + age + gender, id = school_id, family = binomial, corstr = "exchangeable") after sorting by school, whose odds ratio compares all students in program schools with all students in non-program schools. Because the question is whether the program works across schools, the population-averaged GEE odds ratio answers it directly, and 40 schools is enough for the sandwich standard errors; I would expect the GLMM odds ratio to be a little further from 1. For both models I would check that there are enough students meeting the guideline for the number of predictors.Minimum 20 characters required.
Final Knowledge Assessment
1. Which of these studies produces clustered data?
2. In a study in which each participant is measured at four visits, what is the cluster?
3. A mixed model with no predictors gives a between-clinic variance of 10 and a within-clinic variance of 90. What is the ICC?
4. Clusters contain 41 people on average and the ICC is 0.05. What is the design effect?
5. A clustered study of 1,200 people has a design effect of 4. What is its effective sample size?
6. A study of patients in 30 clinics ignores the clinics and treats every patient as independent. What usually happens to the standard error for a clinic-level predictor such as an urban location?
7. In lmer(sbp ~ age + smoker + (1 | clinic_id)), what does (1 | clinic_id) do?
(1 | clinic_id) is a random intercept: each clinic is shifted up or down from the overall average, and the model estimates the variance of these shifts.8. In a linear mixed model of blood pressure, the fixed effect for female is −2.8 mmHg. What does it mean?
9. Which output would show that a mixed model's random-effects part is more complex than the data can support?
10. Which plot checks the assumption that the clinic effects of a mixed model are normally distributed?
ranef(), and a Q-Q plot of them with points near the line supports the normality assumption.11. What does GEE do to account for clustering in a logistic regression?
12. A GLMM gives an odds ratio of 2.3 for urban clinics and GEE gives 2.0. What is the most likely explanation?
13. A GEE analysis has only 8 clusters. What is the main concern?
14. A dataset has one row per person with the columns sbp_0, sbp_6, sbp_12 and sbp_18. What must be done before fitting lmer()?
15. A trial fits lmer(sbp ~ arm * visit + (1 | id)). Some participants missed visits, and missingness depends on their earlier blood pressure. Which statement is correct?
arm:visit interaction.✦ Before submitting: pass every section knowledge check (100%) and complete every reflection.






