Mixed-Effects & Repeated Measures
Measurements from the same subject are not independent. Two readings from one patient are more alike than readings from two patients, and a regression that treats every row as a separate unit gets its standard errors wrong. A mixed-effects model adds a random effect for the subject, so the model knows which rows belong together.
This page fits a random intercept model to a longitudinal study with lme4 in R and statsmodels in Python. It compares that model with a pooled regression, and then tests whether the data support a random slope.
When to use a mixed model
Section titled “When to use a mixed model”Use a mixed model when observations come in groups: repeated measures on one subject, cells from one patient, samples in one batch, patients in one hospital. The random effect carries the variation that the members of a group share. Each fixed effect then gets a standard error that matches its source of information. A comparison within groups is judged against the noise within a group, and a comparison between groups is judged against the number of groups.
Get the data
Section titled “Get the data”Download longitudinal.csv into your working directory. The invented table has 80 rows: 20 subjects, each measured at 4 timepoints. The columns are subject, time, which runs from 0 to 3, and response. The subject is the experimental unit, and each row is one measurement of one subject.
The values come from a simulation with known answers. Each subject has its own baseline, drawn around 50 with a standard deviation of 5. The response falls by 3 per timepoint in every subject, and each measurement carries noise with a standard deviation of 2. No subject has a slope of its own.
library(lme4)library(lmerTest)library(ggplot2)
study <- read.csv("longitudinal.csv")study$subject <- factor(study$subject)dir.create("outputs", showWarnings = FALSE)cat(sprintf("%d rows, %d subjects, %d timepoints\n", nrow(study), nlevels(study$subject), length(unique(study$time))))print(head(study, 4))80 rows, 20 subjects, 4 timepoints subject time response1 S00 0 48.332 S00 1 49.663 S00 2 42.224 S00 3 42.96from pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport statsmodels.formula.api as smffrom scipy import stats
study = pd.read_csv("longitudinal.csv")output = Path("outputs")output.mkdir(exist_ok=True)print(f"{len(study)} rows, {study['subject'].nunique()} subjects, " f"{study['time'].nunique()} timepoints")print(study.head(4))80 rows, 20 subjects, 4 timepoints subject time response0 S00 0 48.331 S00 1 49.662 S00 2 42.223 S00 3 42.96A spaghetti plot draws one line per subject, and a darker line for the mean at each timepoint.
spaghetti <- ggplot(study, aes(time, response, group = subject)) + geom_line(alpha = 0.4, color = "#69b3a2") + geom_point(alpha = 0.4, color = "#69b3a2") + stat_summary(aes(group = 1), fun = mean, geom = "line", color = "#1f4e5f", linewidth = 1.2) + labs(x = "Timepoint", y = "Response") + theme_minimal(base_size = 13)ggsave("outputs/spaghetti-r.png", spaghetti, width = 5, height = 4, dpi = 150, bg = "white")
figure, axes = plt.subplots(figsize=(5, 4))for subject, rows in study.groupby("subject"): axes.plot(rows["time"], rows["response"], color="#4c72b0", alpha=0.4, marker="o")means = study.groupby("time")["response"].mean()axes.plot(means.index, means.values, color="#1f2a44", linewidth=2.5)axes.set_xticks(means.index)axes.set_xlabel("Timepoint")axes.set_ylabel("Response")figure.savefig(output / "spaghetti-python.png", dpi=150, bbox_inches="tight")plt.close(figure)
The lines fall at a similar rate and sit at different heights. A random intercept describes that pattern: one shared slope, and a baseline for each subject.
Fit the random intercept model
Section titled “Fit the random intercept model”The model has a fixed effect of time, which is the trend of interest, and a random intercept for the subject. lme4 writes the random intercept as (1 | subject), and statsmodels takes the grouping column in groups. lmerTest, loaded after lme4, adds Satterthwaite degrees of freedom to the coefficient table.
Both tabs print the fixed effects with Wald 95% confidence intervals, then the variance components and the intraclass correlation, the share of the variance that lies between subjects.
fit <- lmer(response ~ time + (1 | subject), data = study)fixed <- cbind(coef(summary(fit))[, c("Estimate", "Std. Error", "df")], confint(fit, parm = "beta_", method = "Wald"))print(round(fixed, 3))components <- as.data.frame(VarCorr(fit))cat(sprintf("%s variance = %.3f, SD = %.3f\n", components$grp, components$vcov, components$sdcor), sep = "")cat(sprintf("Intraclass correlation = %.3f\n", components$vcov[1] / sum(components$vcov))) Estimate Std. Error df 2.5 % 97.5 %(Intercept) 49.821 0.736 24.4 48.377 51.264time -2.965 0.170 59.0 -3.299 -2.631subject variance = 8.818, SD = 2.969Residual variance = 2.897, SD = 1.702Intraclass correlation = 0.753model = smf.mixedlm("response ~ time", study, groups="subject").fit()interval = model.conf_int().loc[model.fe_params.index]fixed = pd.DataFrame({ "estimate": model.fe_params, "std_error": model.bse_fe, "lower": interval[0], "upper": interval[1],})print(fixed.round(3))subject_variance = model.cov_re.iloc[0, 0]print(f"subject variance = {subject_variance:.3f}, " f"SD = {np.sqrt(subject_variance):.3f}")print(f"Residual variance = {model.scale:.3f}, " f"SD = {np.sqrt(model.scale):.3f}")print("Intraclass correlation = " f"{subject_variance / (subject_variance + model.scale):.3f}") estimate std_error lower upperIntercept 49.821 0.736 48.377 51.264time -2.965 0.170 -3.299 -2.631subject variance = 8.817, SD = 2.969Residual variance = 2.897, SD = 1.702Intraclass correlation = 0.753The two tabs agree on the fixed effects to three decimals. The response falls by 2.965 per timepoint, with a 95% interval from 2.631 to 3.299 that covers the simulated 3.
The df column in the R tab shows what each estimate rests on. The slope has 59 degrees of freedom, which is 80 rows less 20 subject baselines and one slope. The intercept has 24.4, close to the number of subjects, because the average level of the response is a statement about subjects.
The subject variance, 8.818 in R and 8.817 in Python, is three times the residual variance of 2.897. The intraclass correlation is 0.753, so about three quarters of the variance around the time trend lies between subjects.
The fit returns a subject standard deviation of 2.969 where the simulation used 5, and a residual standard deviation of 1.702 where it used 2. The variance between subjects is estimated from 20 baselines, so it is much less certain than the slope. This table is also an unlucky draw: its 20 simulated baselines lie closer together than a standard deviation of 5 usually gives, so the estimate is lower than most tables of this size would return.
Why not ignore the subject?
Section titled “Why not ignore the subject?”A plain regression of the response on time treats the 80 rows as 80 independent units. Fit it beside the mixed model and compare the standard errors.
naive <- lm(response ~ time, data = study)naive_table <- coef(summary(naive))mixed_table <- coef(summary(fit))for (term in rownames(naive_table)) { cat(sprintf("%-11s pooled %.3f (SE %.3f), mixed model %.3f (SE %.3f)\n", term, naive_table[term, "Estimate"], naive_table[term, "Std. Error"], mixed_table[term, "Estimate"], mixed_table[term, "Std. Error"]))}(Intercept) pooled 49.821 (SE 0.634), mixed model 49.821 (SE 0.736)time pooled -2.965 (SE 0.339), mixed model -2.965 (SE 0.170)naive = smf.ols("response ~ time", data=study).fit()for term in naive.params.index: print(f"{term:<11} pooled {naive.params[term]:.3f} " f"(SE {naive.bse[term]:.3f}), " f"mixed model {model.fe_params[term]:.3f} " f"(SE {model.bse_fe[term]:.3f})")Intercept pooled 49.821 (SE 0.634), mixed model 49.821 (SE 0.736)time pooled -2.965 (SE 0.339), mixed model -2.965 (SE 0.170)Both models return the same estimates, because the design is balanced: every subject has the same four timepoints. The standard errors differ, and in opposite directions.
For the time slope, the pooled standard error of 0.339 is twice the mixed model value of 0.170. Time varies within a subject, so each subject serves as its own control. The pooled model gives that up. It leaves the differences between subjects in the residual and judges the slope against all of that noise, so the pooled analysis loses precision.
For the intercept, the pooled standard error of 0.634 is smaller than the mixed model value of 0.736. The average level is a statement about subjects, and 80 correlated rows hold less information about it than 80 independent rows would. Here the pooled analysis claims precision that the study does not have, which is pseudoreplication.
A predictor that is fixed for each subject, such as a treatment group, behaves like the intercept. The pooled standard error of its effect is too small, and its p-value is too small as a result. The pooled model is therefore wrong in both directions, and the direction depends on whether the predictor varies within subjects or between them.
Does the data support a random slope?
Section titled “Does the data support a random slope?”A random intercept lets every subject start at a different level. A random slope also lets every subject change at a different rate. lme4 writes it as (time | subject), and statsmodels takes re_formula="~time". The slope model adds two parameters: the variance of the slopes and their covariance with the intercepts.
A likelihood ratio test compares the two models. The fences fit both by maximum likelihood, which is also what anova() does in lme4 before it compares two mixed models. Each tab prints the two log-likelihoods, the test, and the state of the slope fit.
fit_intercept <- lmer(response ~ time + (1 | subject), data = study, REML = FALSE)fit_slope <- lmer(response ~ time + (time | subject), data = study, REML = FALSE)slope_test <- anova(fit_intercept, fit_slope)cat(sprintf("Log-likelihood: intercept only %.3f, with slope %.3f\n", logLik(fit_intercept), logLik(fit_slope)))cat(sprintf("Likelihood ratio: chi-square = %.3f, df = %d, p = %.3f\n", slope_test$Chisq[2], slope_test$Df[2], slope_test[["Pr(>Chisq)"]][2]))cat(sprintf("Singular fit: %s\n", isSingular(fit_slope)))print(VarCorr(fit_slope))Log-likelihood: intercept only -180.832, with slope -180.722Likelihood ratio: chi-square = 0.219, df = 2, p = 0.896Singular fit: TRUE Groups Name Std.Dev. Corr subject (Intercept) 3.012198 time 0.081037 -1.000 Residual 1.684562def report_slope_test(small, large, label): """Print the likelihood ratio test of a random slope.
Args: small: The fitted random intercept model. large: The fitted model with a random intercept and slope. label: A short name of the optimizer for the printed lines.
Returns: The likelihood ratio statistic. """ statistic = 2 * (large.llf - small.llf) print(f"{label} log-likelihood: intercept only {small.llf:.3f}, " f"with slope {large.llf:.3f}") print(f"{label} likelihood ratio: chi-square = {statistic:.3f}, " f"df = 2, p = {stats.chi2.sf(statistic, 2):.3f}") print(f"{label} converged: {large.converged}") return statistic
fit_intercept = smf.mixedlm("response ~ time", study, groups="subject").fit(reml=False)fit_slope = smf.mixedlm("response ~ time", study, groups="subject", re_formula="~time").fit(reml=False)report_slope_test(fit_intercept, fit_slope, "Default")fit_powell = smf.mixedlm("response ~ time", study, groups="subject", re_formula="~time").fit(reml=False, method=["powell"])report_slope_test(fit_intercept, fit_powell, "Powell")slope_cov = fit_powell.cov_reintercept_sd = np.sqrt(slope_cov.iloc[0, 0])slope_sd = np.sqrt(slope_cov.iloc[1, 1])print(f"Powell SD: intercept {intercept_sd:.3f}, slope {slope_sd:.3f}, " f"correlation {slope_cov.iloc[0, 1] / (intercept_sd * slope_sd):.3f}")Default log-likelihood: intercept only -180.832, with slope -180.820Default likelihood ratio: chi-square = 0.022, df = 2, p = 0.989Default converged: FalsePowell log-likelihood: intercept only -180.832, with slope -180.722Powell likelihood ratio: chi-square = 0.219, df = 2, p = 0.896Powell converged: TruePowell SD: intercept 3.012, slope 0.081, correlation -1.000No test here rejects the random intercept model. That is the expected result, because the simulation gave no subject a slope of its own. The fit of the slope model needs more attention than the p-value.
lme4 prints boundary (singular) fit: see help('isSingular'). The variance table shows the reason: the standard deviation of the slopes is 0.081, and the correlation between intercepts and slopes is -1.000. A correlation of exactly -1 or 1 means that the fit sits on the edge of the allowed parameter values. The data hold no slope variance for the model to find.
statsmodels meets the same edge. Its default optimizers follow the gradient of the likelihood, the likelihood is nearly flat near the edge, and they stop early. statsmodels warns Maximum Likelihood optimization failed to converge. Check mle_retvals, retries with lbfgs and then with cg, and ends with MixedLM optimization failed, trying a different optimizer may help. and Gradient optimization failed, |grad| = 3.128977. The fit that it returns has a log-likelihood of -180.820, which is below the maximum, and gives a statistic of 0.022.
The Powell method does not use the gradient, and neither does the default optimizer of lme4. Powell converges, reaches the log-likelihood of -180.722 that lme4 found, and returns the same statistic of 0.219 and the same variance estimates. statsmodels then warns The MLE may be on the boundary of the parameter space., which is its form of the singular fit message.
The statistic from a fit that did not converge is not the likelihood ratio statistic, and it changes with the optimizer: 0.022 from one and 0.219 from another. The decision is the same here, but a statistic near the critical value would not survive that change. Read a convergence warning as a statement about the number you are about to quote, and refit with another optimizer before you report a test.
The test has a second problem that holds even when the fit converges. The null value, a slope variance of zero, lies on the edge of the allowed values. The correct reference is then a mixture of chi-square distributions with 1 and 2 degrees of freedom, so the plain chi-square with 2 degrees of freedom gives a p-value that is too large. With p = 0.896 the correction changes nothing here. A p-value just above 0.05 from this test deserves a parametric bootstrap, which the lme4 help page ?pvalues lists among its options.
A singular fit says that the model has more random effects parameters than the data can estimate. The remedy is a simpler model, here the random intercept alone.
Mistakes to avoid
Section titled “Mistakes to avoid”- Match the random effect to the design. Repeated timepoints call for a random effect of the subject, and cells from several patients call for a random effect of the patient. The grouping column names the experimental unit.
- Do not read 80 rows as 80 units. The intercept of this model has about 24 degrees of freedom, and the effect of a group assigned per subject would rest on the 20 subjects in the same way.
- Do not add a random slope without a look at the fit. When the data hold no slope variance, the result is a singular fit with a correlation of -1 or 1.
- Do not quote a test statistic from a fit that carries a convergence warning. The default statsmodels fit above returned 0.022 where the maximum gives 0.219.
- A variance component needs enough groups. Twenty subjects returned a subject standard deviation of 2.969 for a simulated 5, an unusually low draw even for this size. More timepoints per subject add little to that estimate, and more subjects add a lot.
- limma’s
duplicateCorrelation()fits the same random intercept structure to each gene and shares one correlation across genes. An expression study with several samples per donor needs it, or a mixed model, for the reason that this page shows.
Scientific references
Section titled “Scientific references”Bates, Mächler, Bolker and Walker, 2015 describe linear mixed-model representation and estimation in lme4.
Kuznetsova, Brockhoff, and Christensen, 2017 describe the lmerTest tests for linear mixed effects models.
Stram and Lee, 1994 derive the reference distribution of the likelihood ratio test for a variance component in a longitudinal mixed model.
Further reading
Section titled “Further reading”The lme4 lmer reference explains the random effects formula and the choice between maximum likelihood and REML. The lme4 page on p-values lists the tests and intervals that lme4 supports, including the parametric bootstrap for a model comparison.
The statsmodels mixed model guide describes MixedLM and the random effects structures that it supports.
The GLMM FAQ by Ben Bolker and others collects practical answers on singular fits, convergence warnings and tests of random effects.
The multiple regression page covers the fixed effects part of this model. The generalized mixed models page extends the random intercept to a binary outcome.