Longitudinal Trials: MMRM
A trial that measures its endpoint at several visits loses patients along the way, and the patients who leave are rarely a random sample. The mixed model for repeated measures, MMRM, is a standard primary analysis for a continuous endpoint in that setting. It uses every observed visit of every patient, estimates the treatment difference at each visit, and stays valid when dropout depends on values that were observed.
This page fits an MMRM to a trial with a known answer, then runs the two analyses it replaced, complete cases and last observation carried forward, on the same table. It builds on ANCOVA and on repeated measures ANOVA.
Get the data
Section titled “Get the data”Download bp_trial_long.csv into your working directory. The invented table holds a randomized trial of 200 patients with hypertension, 100 on placebo and 100 on an active drug. Each row is one observed visit of one patient: patient_id, arm, week (2, 4, 8, or 12), baseline for the systolic pressure before treatment in mmHg, and change for the change from baseline at that visit. The patient is the experimental unit, and the rows of one patient are correlated.
The values come from a simulation with known answers.
- The true mean change is -2, -4, -6, and -8 mmHg on placebo and -12, -15, -17, and -18 mmHg on the active drug. The true treatment difference is therefore -10, -11, -11, and -10 mmHg, and the value at week 12, -10 mmHg, is the target of the trial.
- The correlation between two visits of one patient is 0.7 for neighboring visits and falls to 0.34 between week 2 and week 12. The spread of the change grows from visit to visit.
- After the visits of weeks 2, 4, and 8, a patient with a high pressure at that visit is likely to be withdrawn for rescue therapy, by the same rule in both arms. A withdrawn patient has no later rows.
The first block loads the table and counts the patients observed at each visit, with the mean change among them. On load, mmrm reports that it registered itself as an emmeans extension, and emmeans prints a welcome note.
library(mmrm)library(emmeans)library(ggplot2)
trial <- read.csv("bp_trial_long.csv")trial$arm <- factor(trial$arm, levels = c("placebo", "active"))trial$visit <- factor(trial$week)trial$patient_id <- factor(trial$patient_id)dir.create("outputs", showWarnings = FALSE)truth <- -10
#' Round the numeric columns of a table and print it without row names.#'#' @param table A data frame.#' @param digits The number of decimals to keep.#' @return Invisibly, the rounded data frame.RoundAndPrint <- function(table, digits = 2) { numeric_columns <- vapply(table, is.double, logical(1)) table[numeric_columns] <- round(table[numeric_columns], digits) print(table, row.names = FALSE) invisible(table)}
observed <- aggregate(change ~ week + arm, data = trial, FUN = mean)names(observed)[3] <- "mean_change"observed$patients <- aggregate(change ~ week + arm, data = trial, FUN = length)$changeRoundAndPrint(observed[, c("arm", "week", "patients", "mean_change")]) arm week patients mean_change placebo 2 100 -2.81 placebo 4 77 -5.84 placebo 8 66 -8.03 placebo 12 57 -9.21 active 2 100 -13.17 active 4 91 -16.87 active 8 87 -17.32 active 12 84 -17.85from pathlib import Path
import matplotlib.pyplot as pltimport pandas as pdimport statsmodels.formula.api as smf
trial = pd.read_csv("bp_trial_long.csv")trial["arm"] = pd.Categorical(trial["arm"], categories=["placebo", "active"])output = Path("outputs")output.mkdir(exist_ok=True)truth = -10
observed = (trial.groupby(["arm", "week"], observed=True)["change"] .agg(patients="size", mean_change="mean").reset_index())print(observed.to_string(index=False, float_format="{:.2f}".format)) arm week patients mean_changeplacebo 2 100 -2.81placebo 4 77 -5.84placebo 8 66 -8.03placebo 12 57 -9.21 active 2 100 -13.17 active 4 91 -16.87 active 8 87 -17.32 active 12 84 -17.85Every patient has a week 2 value. By week 12, 57 of the 100 placebo patients remain, against 84 of the 100 on the active drug. The withdrawal rule is the same in both arms. Placebo loses more patients because its pressures stay higher.
The figure draws those means with the number of patients behind each point.
arm_colors <- c(placebo = "#eb6834", active = "#2a78d6")means_plot <- ggplot(observed, aes(x = week, y = mean_change, color = arm)) + geom_line(linewidth = 0.8) + geom_point(size = 2.5) + geom_text(aes(label = patients), color = "grey20", vjust = -1, size = 3.5) + scale_color_manual(values = arm_colors) + scale_x_continuous(breaks = c(2, 4, 8, 12)) + expand_limits(y = 0) + labs(x = "Week", y = "Mean change in systolic pressure (mmHg)", color = NULL) + theme_minimal(base_size = 12) + theme(legend.position = "top", panel.grid.minor = element_blank())ggsave("outputs/mmrm-observed-means-r.png", means_plot, width = 6, height = 4.5, dpi = 150, bg = "white")
arm_colors = {"placebo": "#eb6834", "active": "#2a78d6"}fig, ax = plt.subplots(figsize=(6, 4.5))for arm, color in arm_colors.items(): rows = observed[observed["arm"] == arm] ax.plot(rows["week"], rows["mean_change"], marker="o", color=color, linewidth=2, label=arm) for row in rows.itertuples(): ax.annotate(str(row.patients), (row.week, row.mean_change), textcoords="offset points", xytext=(0, 8), ha="center", color="#333333")ax.set_xticks([2, 4, 8, 12])ax.set_ylim(top=1.5)ax.set_xlabel("Week")ax.set_ylabel("Mean change in systolic pressure (mmHg)")ax.legend(frameon=False, loc="upper right")ax.spines[["top", "right"]].set_visible(False)fig.tight_layout()fig.savefig(output / "mmrm-observed-means-python.png", dpi=150)plt.close(fig)
Each point is the mean of the patients who were still in the trial at that visit. From week 4 on, those are the patients who were not withdrawn, mostly the ones with lower pressures, so a late point does not describe the whole arm. The next block compares the patients who completed the trial with those who were withdrawn.
by_patient <- trial[order(trial$patient_id, trial$week), ]first_rows <- by_patient[!duplicated(by_patient$patient_id), ]carried <- by_patient[!duplicated(by_patient$patient_id, fromLast = TRUE), ]dropout <- data.frame( arm = first_rows$arm, status = ifelse(carried$week == 12, "completed", "withdrawn"), week_2_change = first_rows$change, last_change = carried$change)leavers <- aggregate(cbind(week_2_change, last_change) ~ status + arm, data = dropout, FUN = mean)leavers$patients <- aggregate(last_change ~ status + arm, data = dropout, FUN = length)$last_changeRoundAndPrint(leavers[, c("arm", "status", "patients", "week_2_change", "last_change")]) arm status patients week_2_change last_change placebo completed 57 -5.69 -9.21 placebo withdrawn 43 1.02 4.05 active completed 84 -13.94 -17.85 active withdrawn 16 -9.14 -6.66by_patient = trial.sort_values(["patient_id", "week"])first_rows = by_patient.groupby("patient_id").head(1).set_index("patient_id")carried = by_patient.groupby("patient_id").tail(1).set_index("patient_id")dropout = pd.DataFrame({ "arm": first_rows["arm"], "status": (carried["week"] == 12).map({True: "completed", False: "withdrawn"}), "week_2_change": first_rows["change"], "last_change": carried["change"],})leavers = (dropout.groupby(["arm", "status"], observed=True) .agg(patients=("status", "size"), week_2_change=("week_2_change", "mean"), last_change=("last_change", "mean")).reset_index())print(leavers.to_string(index=False, float_format="{:.2f}".format)) arm status patients week_2_change last_changeplacebo completed 57 -5.69 -9.21placebo withdrawn 43 1.02 4.05 active completed 84 -13.94 -17.85 active withdrawn 16 -9.14 -6.66The two groups already differed at week 2, when everyone was still observed. The 57 placebo patients who completed had a mean change of -5.69 mmHg at week 2, and the 43 who were later withdrawn had 1.02. On the active drug the two means are -13.94 and -9.14, and only 16 patients left. The last value that a withdrawn placebo patient contributed averaged 4.05 mmHg above baseline.
These rows drive everything that follows. An analysis of completers compares 57 selected placebo patients with 84 less selected active patients. An analysis that freezes the last value keeps 4.05 mmHg for 43 placebo patients to the end of a trial in which the placebo arm kept improving.
The model
Section titled “The model”An MMRM is a linear model for the change from baseline with two parts.
- The fixed effects are the baseline value, the arm, the visit as a factor, and the arm by visit interaction. Each arm gets its own mean at every visit, so the model imposes no shape on the time course.
- The four residuals of one patient follow a multivariate normal distribution with a covariance matrix across visits. The unstructured matrix gives every visit its own variance and every pair of visits its own covariance, which is 10 parameters for 4 visits.
Despite the word “mixed”, the model has no random effects. The correlation within a patient sits in the residual covariance matrix. A patient with two observed visits contributes those two, and no row is dropped or filled in.
In the mmrm package, us(visit | patient_id) declares the unstructured matrix. The visit must be a factor, and mmrm() stops with an error when it is numeric. The fit uses restricted maximum likelihood. statsmodels has no equivalent model. Its MixedLM keeps independent residuals with one variance and offers no degrees-of-freedom correction, so the model on this page is fitted in R only.
fit <- mmrm(change ~ baseline + arm * visit + us(visit | patient_id), data = trial)print(summary(fit))mmrm fit
Formula: change ~ baseline + arm * visit + us(visit | patient_id)Data: trial (used 662 observations from 200 subjects with maximum 4timepoints)Covariance: unstructured (10 variance parameters)Method: SatterthwaiteVcov Method: AsymptoticInference: REML
Model selection criteria: AIC BIC logLik deviance 4659.8 4692.8 -2319.9 4639.8
Coefficients: Estimate Std. Error df t value Pr(>|t|)(Intercept) 42.79513 9.50096 188.69000 4.504 1.17e-05 ***baseline -0.28735 0.05963 188.18000 -4.819 2.97e-06 ***armactive -10.56728 1.19088 197.28000 -8.873 4.30e-16 ***visit4 -1.78845 0.86433 166.47000 -2.069 0.0401 *visit8 -3.13828 1.34960 163.31000 -2.325 0.0213 *visit12 -3.96318 1.59550 157.96000 -2.484 0.0140 *armactive:visit4 -1.16070 1.17603 165.58000 -0.987 0.3251armactive:visit8 -0.23200 1.81214 158.60000 -0.128 0.8983armactive:visit12 -0.24351 2.11064 151.03000 -0.115 0.9083---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Covariance estimate: 2 4 8 122 70.8238 56.6793 39.4427 23.09424 56.6793 100.6710 81.8867 45.97468 39.4427 81.8867 139.2765 99.290212 23.0942 45.9746 99.2902 144.3722The header confirms that the fit used all 662 rows from all 200 patients. It also states the inference: restricted maximum likelihood, and the Satterthwaite method for the degrees of freedom, which the package documentation gives as the default. That is why each coefficient has its own fractional df.
The coefficients use placebo and week 2 as reference levels. armactive, -10.57, is the treatment difference at week 2 and at no other visit. The difference at week 12 is the sum of armactive and armactive:visit12, -10.57 plus -0.24. The baseline coefficient of -0.287 says that a patient who starts 10 mmHg higher falls about 2.9 mmHg further at every visit, and the simulation used -0.3.
The covariance estimate shows why the matrix was left unstructured. The variance doubles from 70.8 at week 2 to 144.4 at week 12, and the covariance with week 2 fades from 56.7 at week 4 to 23.1 at week 12.
The treatment difference at each visit
Section titled “The treatment difference at each visit”Nobody should add coefficients by hand. emmeans() computes the adjusted mean of each arm at each visit, at the mean baseline. pairs(reverse = TRUE) takes active minus placebo within each visit, and confint() adds the 95% interval. The mmrm package passes its Satterthwaite degrees of freedom to emmeans for each contrast.
visit_means <- emmeans(fit, ~ arm | visit)differences <- as.data.frame(confint(pairs(visit_means, reverse = TRUE)))RoundAndPrint(differences)visit = 2: contrast estimate SE df lower.CL upper.CL active - placebo -10.57 1.19 197.28 -12.92 -8.22
visit = 4: contrast estimate SE df lower.CL upper.CL active - placebo -11.73 1.49 167.39 -14.68 -8.78
visit = 8: contrast estimate SE df lower.CL upper.CL active - placebo -10.80 1.86 151.44 -14.47 -7.13
visit = 12: contrast estimate SE df lower.CL upper.CL active - placebo -10.81 1.99 143.58 -14.74 -6.88
Confidence level used: 0.95At week 12 the active drug lowers systolic pressure by 10.81 mmHg more than placebo, with a 95% interval from 6.88 to 14.74 mmHg. The true difference is 10. The estimates at weeks 2, 4, and 8 are -10.57, -11.73, and -10.80, against true values of -10, -11, and -11.
The standard error grows from 1.19 at week 2 to 1.99 at week 12. Two causes are visible in the output above. Fewer patients remain, and the variance of the change is larger at late visits. The degrees of freedom fall from 197.28 to 143.58 for the same reasons.
The four intervals carry no adjustment for multiplicity. A trial names one visit as primary in its protocol, here week 12, and the other visits describe the time course.
Compare with complete cases and carried-forward values
Section titled “Compare with complete cases and carried-forward values”Two older analyses reduce the trial to one row per patient and fit an ANCOVA of the change on baseline and arm. The complete-case analysis keeps the 141 patients observed at week 12. Last observation carried forward, LOCF, keeps all 200 and fills the week 12 value of a withdrawn patient with the last change that was observed, which the carried table from the dropout block already holds. The R tab puts both beside the MMRM estimate, and the Python tab runs the two ANCOVA fits with statsmodels.
#' Extract the treatment difference from an ANCOVA fitted with lm().#'#' @param ancova A model from lm() with the term armactive.#' @return A data frame with the estimate, its standard error, and the#' limits of the 95% confidence interval.AncovaDifference <- function(ancova) { limits <- confint(ancova)["armactive", ] data.frame(estimate = coef(ancova)[["armactive"]], se = sqrt(vcov(ancova)["armactive", "armactive"]), lower_95 = limits[[1]], upper_95 = limits[[2]])}
last_visit <- trial[trial$week == 12, ]complete_fit <- lm(change ~ baseline + arm, data = last_visit)locf_fit <- lm(change ~ baseline + arm, data = carried)
mmrm_last <- differences[differences$visit == "12", ]comparison <- rbind( data.frame(estimate = mmrm_last$estimate, se = mmrm_last$SE, lower_95 = mmrm_last$lower.CL, upper_95 = mmrm_last$upper.CL), AncovaDifference(complete_fit), AncovaDifference(locf_fit))comparison$minus_truth <- comparison$estimate - truthcomparison <- cbind( analysis = c("MMRM", "Complete cases", "Carried forward"), patients = c(nlevels(trial$patient_id), nrow(last_visit), nrow(carried)), comparison)RoundAndPrint(comparison) analysis patients estimate se lower_95 upper_95 minus_truth MMRM 200 -10.81 1.99 -14.74 -6.88 -0.81 Complete cases 141 -8.29 2.00 -12.25 -4.33 1.71 Carried forward 200 -12.70 1.74 -16.13 -9.26 -2.70def ancova_difference(ancova, analysis): """Extract the treatment difference from an ANCOVA fitted with ols().
Args: ancova: A fitted statsmodels OLS result with the arm term. analysis: The label of the analysis.
Returns: A dictionary with the label, the number of patients, the estimate, its standard error, and the limits of the 95% confidence interval. """ term = "arm[T.active]" limits = ancova.conf_int().loc[term] return {"analysis": analysis, "patients": int(ancova.nobs), "estimate": ancova.params[term], "se": ancova.bse[term], "lower_95": limits[0], "upper_95": limits[1]}
last_visit = trial[trial["week"] == 12]complete_fit = smf.ols("change ~ baseline + arm", data=last_visit).fit()locf_fit = smf.ols("change ~ baseline + arm", data=carried).fit()
comparison = pd.DataFrame([ ancova_difference(complete_fit, "Complete cases"), ancova_difference(locf_fit, "Carried forward"),])comparison["minus_truth"] = comparison["estimate"] - truthprint(comparison.to_string(index=False, float_format="{:.2f}".format)) analysis patients estimate se lower_95 upper_95 minus_truth Complete cases 141 -8.29 2.00 -12.25 -4.33 1.71Carried forward 200 -12.70 1.74 -16.13 -9.26 -2.70The MMRM estimate is 0.81 mmHg from the truth, less than half of its standard error of 1.99. The complete-case estimate, -8.29, understates the benefit by 1.71 mmHg. The carried-forward estimate, -12.70, overstates it by 2.70 mmHg. The two ANCOVA rows agree between R and Python.
The withdrawal rule predicts both directions.
- The complete-case analysis removes patients with high pressures. It removes 43 from placebo and 16 from the active arm, so the placebo mean improves more than the active mean, and the gap between the arms shrinks.
- The carried-forward analysis freezes each withdrawn patient at a high reading. The placebo arm would have kept improving, from a true mean of -2 mmHg at week 2 to -8 at week 12, and a reading high enough to trigger withdrawal is partly a transient peak. Placebo therefore looks worse at week 12 than it would have been, and the gap widens. The active arm reaches most of its effect by week 2 and loses few patients, so freezing costs it little.
The MMRM neither drops nor freezes a withdrawn patient. It uses the visits that the patient did attend, together with the estimated covariance between visits, to inform the arm mean at the visits that are missing. Under the dropout rule of this simulation that is the correct use of the data.
Read the table with one reservation. All three intervals contain -10, so one trial cannot show that a method is biased; bias is a property of a method over many trials. What one trial shows is that three analyses of the same 200 patients disagree by several mmHg, and that the choice between them belongs in the protocol.
The carried-forward row also has the smallest standard error, 1.74. It counts 59 copied values as if they had been measured at week 12.
Choose the covariance structure
Section titled “Choose the covariance structure”The unstructured matrix makes no assumption about the pattern of variances and correlations, at the price of 10 parameters. Compound symmetry is the opposite extreme, with one variance for all visits and one covariance for all pairs, which is 2 parameters. It is also the structure that a random-intercept model implies. In lmer(change ~ ... + (1 | patient_id)) from the mixed models page, each patient has one shift shared by all visits, which makes every pair of visits equally correlated.
The block fits compound symmetry with cs(), compares the two fits, and then fits the random-intercept model with lme4.
fit_cs <- mmrm(change ~ baseline + arm * visit + cs(visit | patient_id), data = trial)cs_differences <- as.data.frame( confint(pairs(emmeans(fit_cs, ~ arm | visit), reverse = TRUE)))cs_last <- cs_differences[cs_differences$visit == "12", ]structures <- data.frame( covariance = c("unstructured", "compound symmetry"), parameters = c(attr(logLik(fit), "df"), attr(logLik(fit_cs), "df")), aic = c(AIC(fit), AIC(fit_cs)), estimate_week_12 = c(mmrm_last$estimate, cs_last$estimate), se_week_12 = c(mmrm_last$SE, cs_last$SE))RoundAndPrint(structures)
likelihood_ratio <- 2 * as.numeric(logLik(fit) - logLik(fit_cs))extra_parameters <- diff(rev(structures$parameters))cat(sprintf("Likelihood ratio = %.1f on %d df, p = %.2g\n", likelihood_ratio, extra_parameters, pchisq(likelihood_ratio, extra_parameters, lower.tail = FALSE)))cs_matrix <- VarCorr(fit_cs)cat(sprintf("Compound symmetry: variance %.1f, covariance %.1f\n", cs_matrix[1, 1], cs_matrix[1, 2]))
random_intercept <- lme4::lmer( change ~ baseline + arm * visit + (1 | patient_id), data = trial)terms_week_12 <- c("armactive", "armactive:visit12")contrast <- as.numeric(names(lme4::fixef(random_intercept)) %in% terms_week_12)lmer_estimate <- sum(contrast * lme4::fixef(random_intercept))lmer_variance <- contrast %*% as.matrix(vcov(random_intercept)) %*% contrastcat(sprintf("lmer random intercept: estimate %.2f, standard error %.2f\n", lmer_estimate, sqrt(lmer_variance[1, 1]))) covariance parameters aic estimate_week_12 se_week_12 unstructured 10 4659.84 -10.81 1.99 compound symmetry 2 4777.90 -10.70 1.68Likelihood ratio = 134.1 on 8 df, p = 4.1e-25Compound symmetry: variance 105.7, covariance 51.9lmer random intercept: estimate -10.70, standard error 1.68The unstructured fit has the lower AIC, 4659.84 against 4777.90, and the likelihood ratio statistic is 134.1 on 8 degrees of freedom. Both fits have the same fixed effects, so their restricted likelihoods can be compared. Compound symmetry describes these data poorly: it assigns a variance of 105.7 to every visit and a covariance of 51.9 to every pair, while the unstructured estimate has variances from 70.8 to 144.4 and covariances from 23.1 to 99.3.
The estimate at week 12 barely moves, from -10.81 to -10.70. The standard error falls from 1.99 to 1.68. The smaller value is wrong for these data, because compound symmetry gives week 12 a variance averaged over all four visits, and the early visits vary less.
The last line shows that lmer() with a random intercept reproduces the compound symmetry result, -10.70 with a standard error of 1.68. A random-intercept model is a valid mixed model. A trial protocol that says MMRM means the unstructured model, and on this table the random intercept would report an interval that is too narrow.
Name the covariance structure in the analysis plan. The usual choice is unstructured, with a fixed order of simpler structures to try if the fit does not converge, such as the heterogeneous forms toeph(), ar1h(), and csh() of the mmrm package.
What the model assumes about dropout
Section titled “What the model assumes about dropout”The MMRM is valid when the missing values are missing at random. The term means that, given the baseline, the arm, and the changes already observed, the chance of withdrawal does not depend on the values that were never seen. This simulation meets the condition by construction, since the rule read only the pressure of the visit just recorded.
The model gives no protection when dropout depends on the unobserved value itself. A patient whose pressure rose after the last recorded visit and who then left is missing not at random, and the observed data cannot distinguish that case from the first. A trial therefore adds sensitivity analyses that impute the missing values under a stated departure from missing at random. One form assumes that withdrawn patients on the active drug follow the placebo trajectory. Another shifts their imputed values by a growing amount until the conclusion changes.
The target also needs a name. With the visits after rescue therapy treated as missing, this MMRM estimates the difference that would be seen if every patient had stayed on the assigned treatment for 12 weeks.
Mistakes to avoid
Section titled “Mistakes to avoid”- Do not present a carried-forward analysis as conservative. On this table it gave -12.70 against a truth of -10, the most favorable result of the three, with the smallest standard error. The direction of its error depends on which arm loses patients and on how the arms change over time.
- Do not read the arm coefficient as the treatment effect when the model has an arm by visit interaction.
armactiveis the difference at the reference visit, week 2 here, and it changes when you change the reference level. Report the difference at the primary visit fromemmeans(). - Do not enter the visit as a number when the target is the difference at a fixed visit.
change ~ arm * weekwith a numericweekfits one straight line per arm, and the active arm here drops by week 2 and then flattens. The difference at week 12 would then depend on how well a line fits the early visits. - Do not report the result without its ingredients. State the fixed effects, the covariance structure, the method for the degrees of freedom, the software and its version, and the number of patients observed at each visit in each arm.
Scientific references
Section titled “Scientific references”The mmrm package by Sabanes Bove and colleagues fits mixed models for repeated measures.
The emmeans package by Lenth and Piaskowski computes estimated marginal means.
Bates and colleagues, 2015 describe linear mixed-model representation and estimation in lme4.
Mallinckrodt and colleagues, 2008 give recommendations for the primary analysis of continuous endpoints in longitudinal clinical trials.
Siddiqui, Hung, and O’Neill, 2009 compare MMRM with last observation carried forward by simulation and on 48 trial data sets from 25 new drug applications.
Further reading
Section titled “Further reading”The mmrm introduction vignette covers the options that this page leaves at their defaults, such as the adjustment method for the degrees of freedom, weights, and a separate covariance matrix for each arm.
The mmrm covariance structures vignette defines every structure with its formula and its number of parameters. Read it before you write the fallback order of an analysis plan.
The missing data mechanisms page defines missing completely at random, missing at random, and missing not at random, which decide whether the MMRM estimate can be trusted.
The mixed models page fits a random intercept model with lme4 and statsmodels and tests a random slope. Those are the right tools when the grouping is a batch, a donor, or a site and the difference at a fixed visit is not the question.