Repeated Measures ANOVA & Friedman
When the same subjects are measured at every visit, the rows of the table are not independent, and the subject is the experimental unit. A repeated measures ANOVA compares the visit means after it removes the stable differences between subjects. This page runs that analysis on four visits in R and Python, corrects it for a violation of sphericity, estimates each change from baseline, and shows what a mixed model does when visits are missing. For two conditions, the paired tests page is enough.
Get the data
Section titled “Get the data”Download hemoglobin_visits.csv into your working directory. The invented table has 64 rows and three columns: subject_id, week, and hb_g_dl. Sixteen adults with iron deficiency anemia started oral iron, and each had hemoglobin measured in g/dL at baseline and at weeks 2, 4, and 8.
The values come from a simulation with known answers. The true mean is 10.0 g/dL at baseline, and the true mean changes are 0.4, 1.0, and 1.8 g/dL at weeks 2, 4, and 8. Subjects differ in their baseline level with a standard deviation of 0.8 g/dL. Each subject also has an individual rate of response, so a change over a long interval varies more between subjects than a change over a short one. The measurement error has a standard deviation of 0.3 g/dL.
The table is in long format, one row per subject and visit, which the model functions expect. The code also builds a wide table with one row per subject and one column per visit, for the paired steps.
library(lmerTest)library(ggplot2)
hb <- read.csv("hemoglobin_visits.csv")weeks <- c(0, 2, 4, 8)visit_labels <- c("Baseline", "Week 2", "Week 4", "Week 8")hb$visit <- factor(hb$week, levels = weeks, labels = visit_labels)wide <- tidyr::pivot_wider(hb, id_cols = subject_id, names_from = week, values_from = hb_g_dl, names_prefix = "week_")visit_values <- as.matrix(wide[, -1])dir.create("outputs", showWarnings = FALSE)cat(sprintf("%d rows, %d subjects, %d visits per subject\n", nrow(hb), nrow(wide), ncol(visit_values)))cat(sprintf("%-8s mean = %4.1f, SD = %.2f\n", visit_labels, colMeans(visit_values), apply(visit_values, 2, sd)), sep = "")64 rows, 16 subjects, 4 visits per subjectBaseline mean = 9.8, SD = 0.97Week 2 mean = 10.3, SD = 0.80Week 4 mean = 10.8, SD = 0.88Week 8 mean = 11.6, SD = 1.02import itertoolsfrom pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport pingouin as pgimport statsmodels.formula.api as smffrom scipy import statsfrom statsmodels.stats.anova import AnovaRMfrom statsmodels.stats.multitest import multipletests
hb = pd.read_csv("hemoglobin_visits.csv")weeks = [0, 2, 4, 8]visit_labels = ["Baseline", "Week 2", "Week 4", "Week 8"]wide = hb.pivot(index="subject_id", columns="week", values="hb_g_dl")output = Path("outputs")output.mkdir(exist_ok=True)print(f"{len(hb)} rows, {len(wide)} subjects, " f"{wide.shape[1]} visits per subject")for week, label in zip(weeks, visit_labels): print(f"{label:<8} mean = {wide[week].mean():4.1f}, " f"SD = {wide[week].std():.2f}")64 rows, 16 subjects, 4 visits per subjectBaseline mean = 9.8, SD = 0.97Week 2 mean = 10.3, SD = 0.80Week 4 mean = 10.8, SD = 0.88Week 8 mean = 11.6, SD = 1.02The visit means rise from 9.8 to 11.6 g/dL. The standard deviation within a visit is close to 1 g/dL, about half of the rise over eight weeks.
Look at each subject
Section titled “Look at each subject”Draw one line per subject before any test. The visit means describe the group, and the lines show whether the subjects follow them.
trajectories <- ggplot(hb, aes(week, hb_g_dl)) + geom_line(aes(group = subject_id), color = "gray70", linewidth = 0.4) + stat_summary(fun = mean, geom = "line", color = "#1f4e5f", linewidth = 1.2) + stat_summary(fun = mean, geom = "point", color = "#1f4e5f", size = 3) + scale_x_continuous(breaks = weeks, labels = visit_labels) + labs(x = NULL, y = "Hemoglobin (g/dL)", title = "Each subject (gray) and the visit means (dark)") + theme_classic(base_size = 12)ggsave("outputs/repeated-trajectories-r.png", trajectories, width = 6, height = 4, dpi = 150)
figure, axes = plt.subplots(figsize=(6, 4))axes.plot(weeks, wide.to_numpy().T, color="0.75", linewidth=0.8)axes.plot(weeks, wide.mean(), color="#1f2a44", linewidth=2.5, marker="o", markersize=8)axes.set_xticks(weeks, visit_labels)axes.set_ylabel("Hemoglobin (g/dL)")axes.set_title("Each subject (gray) and the visit means (dark)")axes.spines[["top", "right"]].set_visible(False)figure.tight_layout()figure.savefig(output / "repeated-trajectories-python.png", dpi=150)plt.close(figure)
The gray lines sit at different heights and mostly rise together. A subject who starts high stays high, so the spread at one visit is mostly a spread between people. The analysis below removes it, because the question is whether hemoglobin changes within a person.
The subject is the unit
Section titled “The subject is the unit”A one-way ANOVA on the 64 rows treats them as 64 independent people. That is wrong for this design, and it is printed here only to show what the pairing changes. The repeated measures ANOVA splits the variation into a part between subjects and a part within subjects, and it tests the visits against the within-subject part alone.
In R, aov() takes an Error(subject_id) term that names the subject stratum. In Python, rm_anova() from pingouin takes the subject column.
ignore_pairing <- summary(aov(hb_g_dl ~ visit, data = hb))[[1]]strata <- summary(aov(hb_g_dl ~ visit + Error(subject_id), data = hb))within <- strata[["Error: Within"]][[1]]cat(sprintf("%-24s F(%d, %d) = %.2f, p = %.2g, error mean square = %.3f\n", c("One-way ANOVA on rows:", "Repeated measures ANOVA:"), c(ignore_pairing$Df[1], within$Df[1]), c(ignore_pairing$Df[2], within$Df[2]), c(ignore_pairing[["F value"]][1], within[["F value"]][1]), c(ignore_pairing[["Pr(>F)"]][1], within[["Pr(>F)"]][1]), c(ignore_pairing[["Mean Sq"]][2], within[["Mean Sq"]][2])), sep = "")One-way ANOVA on rows: F(3, 60) = 11.45, p = 4.9e-06, error mean square = 0.851Repeated measures ANOVA: F(3, 45) = 51.02, p = 1.6e-14, error mean square = 0.191samples = [wide[week] for week in weeks]ignore_pairing = stats.f_oneway(*samples)pooled_variance = wide.var().mean()print(f"{'One-way ANOVA on rows:':<24} " f"F({len(weeks) - 1}, {len(hb) - len(weeks)}) = " f"{ignore_pairing.statistic:.2f}, p = {ignore_pairing.pvalue:.2g}, " f"error mean square = {pooled_variance:.3f}")repeated = pg.rm_anova(data=hb, dv="hb_g_dl", within="week", subject="subject_id", correction=True, detailed=True)print(f"{'Repeated measures ANOVA:':<24} " f"F({repeated.loc[0, 'DF']:.0f}, {repeated.loc[1, 'DF']:.0f}) = " f"{repeated.loc[0, 'F']:.2f}, p = {repeated.loc[0, 'p_unc']:.2g}, " f"error mean square = {repeated.loc[1, 'MS']:.3f}")One-way ANOVA on rows: F(3, 60) = 11.45, p = 4.9e-06, error mean square = 0.851Repeated measures ANOVA: F(3, 45) = 51.02, p = 1.6e-14, error mean square = 0.191Both analyses have the same numerator, the variation between the four visit means. The denominators differ. The one-way error mean square, 0.851, contains the spread between subjects. The repeated measures error mean square, 0.191, contains only the part of each subject’s profile that the subject’s own level and the visit means do not explain. F rises from 11.45 to 51.02, and the error degrees of freedom fall from 60 to 45, because 15 of them now describe the 16 subjects.
The larger F is a consequence and not the reason to choose the analysis. The design decides: one group of people, each measured four times.
Sphericity
Section titled “Sphericity”The repeated measures F-test assumes sphericity: the difference between two visits has the same variance for every pair of visits. With four visits there are six such differences. When their variances differ, the uncorrected F-test rejects too often.
Mauchly’s test takes sphericity as its null hypothesis. A small p-value counts against sphericity. A large p-value from 16 subjects would not establish it, so the test cannot tell you that the uncorrected F is safe. The Greenhouse-Geisser correction does not depend on that decision. It estimates epsilon, which is 1 under sphericity and falls to 1/(k − 1) for k visits at the worst, and it multiplies both degrees of freedom by epsilon.
anova_test() from rstatix returns the ANOVA table, Mauchly’s test, and the correction in one list. rm_anova() from pingouin returned them above, as columns of the same table.
visit_pairs <- combn(length(weeks), 2)for (index in seq_len(ncol(visit_pairs))) { first <- visit_pairs[1, index] second <- visit_pairs[2, index] difference <- visit_values[, second] - visit_values[, first] cat(sprintf("Week %d minus week %d: variance of the difference = %.3f\n", weeks[second], weeks[first], var(difference)))}repeated <- rstatix::anova_test(hb, dv = hb_g_dl, wid = subject_id, within = visit)mauchly <- repeated[["Mauchly's Test for Sphericity"]]correction <- repeated[["Sphericity Corrections"]]cat(sprintf("Mauchly W = %.3f, p = %.3g\n", mauchly$W, mauchly$p))cat(sprintf("Greenhouse-Geisser epsilon = %.3f\n", correction$GGe))cat(sprintf("Uncorrected F(%d, %d) = %.2f, p = %.2g\n", repeated$ANOVA$DFn, repeated$ANOVA$DFd, repeated$ANOVA$F, repeated$ANOVA$p))cat(sprintf("Corrected F(%s) = %.2f, p = %.2g\n", correction[["DF[GG]"]], repeated$ANOVA$F, correction[["p[GG]"]]))Week 2 minus week 0: variance of the difference = 0.138Week 4 minus week 0: variance of the difference = 0.280Week 8 minus week 0: variance of the difference = 0.868Week 4 minus week 2: variance of the difference = 0.106Week 8 minus week 2: variance of the difference = 0.517Week 8 minus week 4: variance of the difference = 0.383Mauchly W = 0.168, p = 0.000185Greenhouse-Geisser epsilon = 0.492Uncorrected F(3, 45) = 51.02, p = 1.6e-14Corrected F(1.48, 22.14) = 51.02, p = 3.4e-08for first, second in itertools.combinations(weeks, 2): difference = wide[second] - wide[first] print(f"Week {second} minus week {first}: " f"variance of the difference = {difference.var():.3f}")effect = repeated.loc[0]error_df = repeated.loc[1, "DF"]print(f"Mauchly W = {effect['W_spher']:.3f}, p = {effect['p_spher']:.3g}")print(f"Greenhouse-Geisser epsilon = {effect['eps']:.3f}")print(f"Uncorrected F({effect['DF']:.0f}, {error_df:.0f}) = " f"{effect['F']:.2f}, p = {effect['p_unc']:.2g}")print(f"Corrected F({effect['DF'] * effect['eps']:.2f}, " f"{error_df * effect['eps']:.2f}) = {effect['F']:.2f}, " f"p = {effect['p_GG_corr']:.2g}")Week 2 minus week 0: variance of the difference = 0.138Week 4 minus week 0: variance of the difference = 0.280Week 8 minus week 0: variance of the difference = 0.868Week 4 minus week 2: variance of the difference = 0.106Week 8 minus week 2: variance of the difference = 0.517Week 8 minus week 4: variance of the difference = 0.383Mauchly W = 0.168, p = 0.000185Greenhouse-Geisser epsilon = 0.492Uncorrected F(3, 45) = 51.02, p = 1.6e-14Corrected F(1.48, 22.14) = 51.02, p = 3.4e-08The six variances run from 0.106 to 0.868, an eightfold range. The largest belongs to week 8 minus baseline, the longest interval, which is what the simulation built in. Mauchly’s test counts against sphericity as well, with W = 0.168 and p = 0.000185.
Epsilon is 0.492, closer to its lower bound of 1/3 for four visits than to 1. The F statistic stays at 51.02 and its reference distribution changes: the degrees of freedom shrink from (3, 45) to (1.48, 22.14), and the p-value grows from 1.6e-14 to 3.4e-08. The conclusion survives here by a wide margin. In a study with a smaller effect, halving the degrees of freedom can change the conclusion, so report the corrected test whenever the visits are ordered in time. Measurements that are close in time are usually more alike than measurements that are far apart, and that pattern alone breaks sphericity.
Changes from baseline
Section titled “Changes from baseline”The F-test says that the visit means are not all equal. The clinical result is the size of each change. A paired t-test on each later visit against baseline estimates it, and the family has three comparisons, as the post hoc comparisons page explains. The code adjusts the three p-values with Holm’s method and prints Bonferroni intervals at a level of 1 − 0.05/3, which cover all three changes together with at least 95% confidence.
Each paired test uses only the two visits in the comparison, so it does not depend on sphericity.
changes <- data.frame(week = weeks[-1], estimate = NA, lower = NA, upper = NA, p = NA)for (row in seq_len(nrow(changes))) { paired <- t.test(visit_values[, row + 1], visit_values[, 1], paired = TRUE, conf.level = 1 - 0.05 / 3) changes[row, -1] <- c(paired$estimate, paired$conf.int, paired$p.value)}changes$p_holm <- p.adjust(changes$p, method = "holm")cat(sprintf("Week %d minus baseline: %.2f g/dL [%.2f, %.2f], Holm p = %.2g\n", changes$week, changes$estimate, changes$lower, changes$upper, changes$p_holm), sep = "")Week 2 minus baseline: 0.49 g/dL [0.24, 0.74], Holm p = 8.6e-05Week 4 minus baseline: 0.98 g/dL [0.62, 1.34], Holm p = 4.3e-06Week 8 minus baseline: 1.83 g/dL [1.20, 2.46], Holm p = 3.2e-06paired_tests = [stats.ttest_rel(wide[week], wide[0]) for week in weeks[1:]]holm = multipletests([test.pvalue for test in paired_tests], method="holm")[1]for week, test, p_holm in zip(weeks[1:], paired_tests, holm): interval = test.confidence_interval(1 - 0.05 / 3) change = (wide[week] - wide[0]).mean() print(f"Week {week} minus baseline: {change:.2f} g/dL " f"[{interval.low:.2f}, {interval.high:.2f}], Holm p = {p_holm:.2g}")Week 2 minus baseline: 0.49 g/dL [0.24, 0.74], Holm p = 8.6e-05Week 4 minus baseline: 0.98 g/dL [0.62, 1.34], Holm p = 4.3e-06Week 8 minus baseline: 1.83 g/dL [1.20, 2.46], Holm p = 3.2e-06Hemoglobin rose by 0.49 g/dL at week 2, 0.98 at week 4, and 1.83 at week 8. The true changes of the simulation, 0.4, 1.0, and 1.8, all lie inside their intervals. The week 8 interval is the widest, because the week 8 difference has the largest variance of the three, 0.868.
A question about ranks: the Friedman test
Section titled “A question about ranks: the Friedman test”The Friedman test ranks the four visits within each subject, from 1 for the lowest hemoglobin to 4 for the highest, and asks whether the mean rank is the same at every visit. It is a test of the ordering within subjects. It does not use the size of any change, so a rise of 0.1 g/dL and a rise of 3 g/dL count the same. Choose it when the ordering is the claim, or when the scale gives order and not distance, such as a symptom grade. It does not estimate a change in g/dL.
friedman <- friedman.test(visit_values)within_ranks <- t(apply(visit_values, 1, rank))cat(sprintf("%-8s mean rank = %.2f\n", visit_labels, colMeans(within_ranks)), sep = "")cat(sprintf("Friedman chi-square = %.2f, df = %d, p = %.2g\n", friedman$statistic, friedman$parameter, friedman$p.value))cat(sprintf("Kendall's W = %.3f\n", friedman$statistic / (nrow(visit_values) * (length(weeks) - 1))))Baseline mean rank = 1.16Week 2 mean rank = 2.03Week 4 mean rank = 3.06Week 8 mean rank = 3.75Friedman chi-square = 37.72, df = 3, p = 3.2e-08Kendall's W = 0.786friedman = stats.friedmanchisquare(*samples)within_ranks = wide.rank(axis=1)for week, label in zip(weeks, visit_labels): print(f"{label:<8} mean rank = {within_ranks[week].mean():.2f}")print(f"Friedman chi-square = {friedman.statistic:.2f}, " f"df = {len(weeks) - 1}, p = {friedman.pvalue:.2g}")kendall_w = friedman.statistic / (len(wide) * (len(weeks) - 1))print(f"Kendall's W = {kendall_w:.3f}")Baseline mean rank = 1.16Week 2 mean rank = 2.03Week 4 mean rank = 3.06Week 8 mean rank = 3.75Friedman chi-square = 37.72, df = 3, p = 3.2e-08Kendall's W = 0.786The mean ranks climb from 1.16 at baseline to 3.75 at week 8. If every subject had the order baseline, week 2, week 4, week 8, the mean ranks would be exactly 1, 2, 3, and 4. Kendall’s W rescales the statistic to run from 0, no shared ordering, to 1, the same ordering in every subject, and it is 0.786 here.
The same test as a mixed model
Section titled “The same test as a mixed model”A linear mixed model with a random intercept for each subject describes the same structure: each subject has an individual level, and the visit means are fixed effects. On complete and balanced data with a subject variance estimate above zero, its test of the visit effect is the uncorrected repeated measures F-test.
lmer() with lmerTest loaded reports an F-test with Satterthwaite degrees of freedom. mixedlm() in statsmodels reports a Wald chi-square test for the three visit coefficients together, without denominator degrees of freedom. The Python code divides the chi-square by its 3 degrees of freedom to get the F statistic, and reads the p-value from an F distribution with the 45 error degrees of freedom of the balanced design.
mixed <- lmer(hb_g_dl ~ visit + (1 | subject_id), data = hb)mixed_test <- anova(mixed)cat(sprintf("Mixed model F(%d, %.0f) = %.2f, p = %.2g\n", mixed_test$NumDF, mixed_test$DenDF, mixed_test[["F value"]], mixed_test[["Pr(>F)"]]))variance <- as.data.frame(VarCorr(mixed))cat(sprintf("Subject SD = %.3f, residual SD = %.3f\n", variance$sdcor[1], variance$sdcor[2]))Mixed model F(3, 45) = 51.02, p = 1.6e-14Subject SD = 0.812, residual SD = 0.437mixed = smf.mixedlm("hb_g_dl ~ C(week)", hb, groups="subject_id").fit()wald = mixed.wald_test_terms().table.loc["C(week)"]f_value = wald["statistic"] / wald["df_constraint"]print(f"Wald chi-square = {wald['statistic']:.2f} on " f"{wald['df_constraint']:.0f} df, p = {wald['pvalue']:.2g}")print(f"Mixed model F({wald['df_constraint']:.0f}, {error_df:.0f}) = " f"{f_value:.2f}, p = " f"{stats.f.sf(f_value, wald['df_constraint'], error_df):.2g}")print(f"Subject SD = {np.sqrt(mixed.cov_re.iloc[0, 0]):.3f}, " f"residual SD = {np.sqrt(mixed.scale):.3f}")Wald chi-square = 153.06 on 3 df, p = 5.8e-33Mixed model F(3, 45) = 51.02, p = 1.6e-14Subject SD = 0.812, residual SD = 0.437The mixed model returns F(3, 45) = 51.02 and p = 1.6e-14, the uncorrected repeated measures result to every printed digit. The chi-square of 153.06 is three times that F. Its own p-value, 5.8e-33, treats the residual variance as known and is far too small for 16 subjects, which is why the code converts it.
The agreement is algebra and not a second opinion. The random intercept model assumes one variance for the subject levels and one for the residuals. That structure, compound symmetry, is a special case of sphericity, so the mixed model inherits the problem that the Greenhouse-Geisser correction addresses. The subject standard deviation of 0.812 g/dL is close to the true 0.8. The residual standard deviation of 0.437 is above the true measurement error of 0.3, because it also absorbs the subject-specific responses that this model has no term for. The mixed models page adds a random slope, and the MMRM page fits an unstructured covariance matrix across visits.
When visits are missing
Section titled “When visits are missing”The two analyses part ways when the table has holes. The code below removes four of the 64 rows: week 8 of subject S04, weeks 4 and 8 of S09, and week 2 of S13.
missing <- (hb$subject_id == "S04" & hb$week == 8) | (hb$subject_id == "S09" & hb$week >= 4) | (hb$subject_id == "S13" & hb$week == 2)incomplete <- hb[!missing, ]cat(sprintf("Rows kept: %d of %d\n", nrow(incomplete), nrow(hb)))incomplete_anova <- rstatix::anova_test(incomplete, dv = hb_g_dl, wid = subject_id, within = visit)$ANOVAcat(sprintf("Repeated measures ANOVA: F(%d, %d) = %.2f, subjects used = %d\n", incomplete_anova$DFn, incomplete_anova$DFd, incomplete_anova$F, incomplete_anova$DFd / incomplete_anova$DFn + 1))incomplete_mixed <- lmer(hb_g_dl ~ visit + (1 | subject_id), data = incomplete)incomplete_test <- anova(incomplete_mixed)cat(sprintf("Mixed model: F(%d, %.2f) = %.2f, rows used = %d, ", incomplete_test$NumDF, incomplete_test$DenDF, incomplete_test[["F value"]], nobs(incomplete_mixed)))cat(sprintf("subjects used = %d\n", ngrps(incomplete_mixed)))complete_cases <- na.omit(tidyr::pivot_wider( incomplete, id_cols = subject_id, names_from = week, values_from = hb_g_dl, names_prefix = "week_"))cat(sprintf("Week 8 change, %d complete cases: %.2f g/dL\n", nrow(complete_cases), mean(complete_cases$week_8 - complete_cases$week_0)))cat(sprintf("Week 8 change, mixed model: %.2f g/dL\n", fixef(incomplete_mixed)[["visitWeek 8"]]))Rows kept: 60 of 64Repeated measures ANOVA: F(3, 36) = 61.61, subjects used = 13Mixed model: F(3, 41.19) = 67.55, rows used = 60, subjects used = 16Week 8 change, 13 complete cases: 1.93 g/dLWeek 8 change, mixed model: 1.93 g/dLmissing = (((hb["subject_id"] == "S04") & (hb["week"] == 8)) | ((hb["subject_id"] == "S09") & (hb["week"] >= 4)) | ((hb["subject_id"] == "S13") & (hb["week"] == 2)))incomplete = hb[~missing]print(f"Rows kept: {len(incomplete)} of {len(hb)}")try: AnovaRM(incomplete, "hb_g_dl", "subject_id", within=["week"]).fit()except ValueError as error: print(f"statsmodels AnovaRM stops: {error}")incomplete_anova = pg.rm_anova(data=incomplete, dv="hb_g_dl", within="week", subject="subject_id", detailed=True)anova_df = incomplete_anova["DF"]print(f"Repeated measures ANOVA: F({anova_df[0]:.0f}, {anova_df[1]:.0f}) = " f"{incomplete_anova.loc[0, 'F']:.2f}, " f"subjects used = {anova_df[1] / anova_df[0] + 1:.0f}")incomplete_mixed = smf.mixedlm("hb_g_dl ~ C(week)", incomplete, groups="subject_id").fit()incomplete_wald = incomplete_mixed.wald_test_terms().table.loc["C(week)"]print(f"Mixed model: Wald chi-square / 3 = " f"{incomplete_wald['statistic'] / 3:.2f}, " f"rows used = {incomplete_mixed.nobs:.0f}, " f"subjects used = {incomplete_mixed.model.n_groups}")complete_cases = incomplete.pivot(index="subject_id", columns="week", values="hb_g_dl").dropna()print(f"Week 8 change, {len(complete_cases)} complete cases: " f"{(complete_cases[8] - complete_cases[0]).mean():.2f} g/dL")print(f"Week 8 change, mixed model: " f"{incomplete_mixed.params['C(week)[T.8]']:.2f} g/dL")Rows kept: 60 of 64statsmodels AnovaRM stops: Data is unbalanced.Repeated measures ANOVA: F(3, 36) = 61.61, subjects used = 13Mixed model: Wald chi-square / 3 = 67.55, rows used = 60, subjects used = 16Week 8 change, 13 complete cases: 1.93 g/dLWeek 8 change, mixed model: 1.93 g/dLA repeated measures ANOVA needs every subject at every visit. anova_test() and rm_anova() drop the three subjects with a missing visit and print no message: the error degrees of freedom of 36 are the only sign that 13 subjects remain. The eight observed rows of those subjects go with the four missing ones. AnovaRM in statsmodels stops with an error. The mixed model uses all 60 rows from all 16 subjects, and S13 still contributes a baseline, a week 4, and a week 8 value.
Using every row is not the same as recovering what was lost. S09 is the subject whose line falls from 11.1 to 10.4 g/dL after week 4 in the figure, and the removal took away its last two visits. Both week 8 estimates are now 1.93 g/dL, above the 1.83 of the complete table. A mixed model gives valid estimates when the chance that a visit is missing depends only on values that were observed. If patients who do not respond stop attending, and nothing in the recorded data shows it, no choice between these two analyses repairs the estimate.
Mistakes to avoid
Section titled “Mistakes to avoid”Do not run a one-way ANOVA or unpaired t-tests on repeated measures. The 64 rows here are 16 people, and an analysis that counts 64 units misstates both the error variance and its degrees of freedom.
Do not treat a nonsignificant Mauchly’s test as permission to skip the correction. A large p-value from 16 subjects does not show that sphericity holds.
Do not let software choose your sample. After any repeated measures ANOVA, read the error degrees of freedom and confirm that (subjects − 1) × (visits − 1) matches the number of subjects you enrolled.
Do not present agreement between the repeated measures ANOVA and the random intercept model as a check of either, because they are one model fitted two ways.
Do not reach for the Friedman test because a normality test rejected. It answers a question about ordering, and it cannot return a change in g/dL.
Report the result
Section titled “Report the result”Give the test with its corrected degrees of freedom, then the changes with their intervals: “Hemoglobin changed over the four visits (repeated measures ANOVA with Greenhouse-Geisser correction, epsilon = 0.49, F(1.48, 22.14) = 51.02, p = 3.4e-08; 16 subjects). It rose from baseline by 0.49 g/dL at week 2 (simultaneous 95% CI 0.24 to 0.74), by 0.98 g/dL at week 4 (0.62 to 1.34), and by 1.83 g/dL at week 8 (1.20 to 2.46).”
Scientific references
Section titled “Scientific references”Greenhouse and Geisser, 1959 describe the adjustment of the F-test degrees of freedom for profile data with an arbitrary covariance matrix.
Mauchly, 1940 describes the significance test for sphericity of a multivariate normal distribution.
Friedman, 1937 describes the use of ranks within blocks to avoid the normality assumption of the analysis of variance.
Bates and colleagues, 2015 describe linear mixed-model representation and estimation in lme4.
Kuznetsova, Brockhoff, and Christensen, 2017 describe the lmerTest tests for linear mixed effects models.
Vallat, 2018 describes Pingouin, the Python statistics package that supplies the repeated measures ANOVA with its sphericity test and correction here.
Further reading
Section titled “Further reading”The rstatix anova_test reference documents the wid and within arguments and get_anova_table(), which reports the table with corrected or uncorrected degrees of freedom.
The pingouin rm_anova reference gives the sums of squares behind the F-test. It states that the function removes every subject with a missing value, and it recommends a mixed model when many values are missing.
The statsmodels MixedLM guide describes the two types of random effects that mixedlm() accepts: random coefficients with an unknown covariance matrix, and variance components.
The paired tests page covers two conditions. The mixed models page explains the random intercept model and tests a random slope, and the MMRM page handles longitudinal trials with an unstructured covariance matrix and missing visits.