Skip to main content
v2026.11,986 entries · CC-BY 4.0

Repeated-Measures ANOVA in R: aov(), rstatix and afex

Run a repeated-measures ANOVA in R with aov(), rstatix or afex: long-format data, sphericity correction, output columns and fixes for common errors.

Written and maintained by CASRAI Editorial Board

Published · Last updated

On this page

A repeated-measures ANOVA in R tests whether the mean of an outcome differs across conditions or time points measured on the same subjects. You need long-format data with one row per subject per condition, a subject ID stored as a factor, and one of three routes: base R aov() with an Error() term, rstatix::anova_test(), or afex::aov_ez(). The routes fit the same kind of model but differ in what they report by default, above all in how they handle the sphericity assumption.

What a repeated-measures ANOVA in R is used for in research

Use it when every participant, animal, sample or site contributes a measurement under each level of a within-subject factor, for example the same participants scored at baseline, week 4 and week 8, or the same cell cultures measured under three treatments. Because each subject serves as its own control, the error term is partitioned into strata, and that is why a plain one-way aov(score ~ time) is wrong for this design: it treats repeated rows from one subject as independent observations. The assumptions behind the test, including sphericity, are covered in repeated-measures ANOVA assumptions; this page is the R workflow.

All three routes below accept within-subject factors, between-subject factors (a mixed design) and, in the packages, covariates. Pick the route by what you need in the output, not by which one a tutorial happened to use first.

Install and access: R and CRAN packages only

Base R ships aov() in the stats package, so the first route needs no installation. The other two routes come from CRAN, the official package repository. As listed on CRAN when checked on 2026-11-15, rstatix is at version 1.1.0 (released 2026-07-23, GPL-2 licence, described as a pipe-friendly framework for basic statistical tests) and afex is at version 1.5-1 (released 2025-12-14, described as analysis of factorial experiments). Install them from inside R:

install.packages(c("rstatix", "afex"))library(rstatix)library(afex)

Always take packages from CRAN or the maintainers’ own repositories, and record the package versions you used so the analysis can be reproduced.

Step-by-step: run a repeated-measures ANOVA in R

The steps use a hypothetical data frame called scores with three columns: id (subject), time (the within-subject factor, with levels such as baseline, week4 and week8) and score (the outcome). Replace the names with your own.

  1. Put the data in long format. Each row must be one subject-by-condition observation. If your file has one column per time point, reshape it first; the guide to pivoting to long format in R shows how, typically with tidyr::pivot_longer(cols = ..., names_to = "time", values_to = "score").
  2. Make the ID and the factor real factors. scores$id = factor(scores$id) and scores$time = factor(scores$time). A numeric ID is read as a continuous variable by aov() and silently gives the wrong error strata.
  3. Check that the design is balanced. with(scores, table(id, time)) should show exactly one observation in every cell. The R documentation for aov() states that the function is designed for balanced designs, that results can be hard to interpret without balance, and that missing values will likely lose the balance. The replications() function it points to is the documented way to check balance for a formula.
  4. Run the model with whichever route you chose (next three subsections).
  5. Check sphericity and apply a correction if the within-subject factor has three or more levels (see the output section).
  6. Follow up with post hoc comparisons only if the omnibus effect warrants it, and report an effect size.

Route 1: base R aov() with an Error() term

fit = aov(score ~ time + Error(id/time), data = scores)summary(fit)

The R manual for aov() says that if the formula contains a single Error term, it is used to specify error strata. Here Error(id/time) declares subjects as the stratum and time nested within them. The manual also notes that contrasts are not used for Error terms and that weights should not be used together with Error. The output is a set of ANOVA tables, one per stratum; the test of time is in the id:time stratum. Base summary() does not print a sphericity test or a corrected p-value, so on its own this route leaves the assumption unchecked.

Route 2: rstatix::anova_test()

res = anova_test(data = scores, dv = score, wid = id, within = time)resget_anova_table(res, correction = "auto")

The rstatix reference documents the signature anova_test(data, formula, dv, wid, between, within, covariate, type = NULL, effect.size = "ges", error = NULL, white.adjust = FALSE, observed = NULL, detailed = FALSE, ci = NULL). wid is the subject identifier column and must be unique per individual; within names the within-subject factors; repeated-measures designs use Type III sums of squares. The default effect size is generalized eta squared ("ges"); set effect.size = "pes" for partial eta squared and detailed = TRUE to add the sums-of-squares columns and the intercept. For a two-factor within design the documentation shows the formula interface as well, in the pattern anova_test(len ~ supp*dose + Error(id/(supp*dose))), equivalent to the dv/wid/within form.

Route 3: afex::aov_ez()

fit3 = aov_ez(id = "id", dv = "score", data = scores, within = "time")fit3nice(fit3)

The afex reference manual gives aov_ez(id, dv, data, between = NULL, within = NULL, covariate = NULL, observed = NULL, fun_aggregate = NULL, ...). id and dv are single character strings (quoted column names, unlike rstatix), and the data must be in long format. The sphericity correction is set through anova_table = list(correction = ..., es = ...); the correction defaults to Greenhouse-Geisser ("GG"), with Huynh-Feldt or none as alternatives. If there are several observations per subject-by-condition cell, the default fun_aggregate = NULL warns and uses the mean; passing fun_aggregate = mean makes that explicit and silences the warning. For a mixed design add between = "group". The afex guide goes deeper into mixed designs.

Output and how to read it

Whichever route you use, read three things in order: the sphericity check, the (corrected) F test for the within-subject factor, and the effect size.

  • Sphericity. With three or more within-subject levels, rstatix prints Mauchly’s test for each within factor. Its get_anova_table() accepts correction = c("auto", "GG", "HF", "none"), and "auto" applies the Greenhouse-Geisser correction only to factors whose Mauchly p-value is 0.05 or below. afex applies Greenhouse-Geisser by default regardless of the Mauchly result. Background on the test and the epsilon estimates is in the Mauchly’s test of sphericity guide.
  • The F test. The main table lists the effect, numerator and denominator degrees of freedom (DFn, DFd), F and p. When a correction is applied, the corrected degrees of freedom and p-value replace the uncorrected ones for that effect: report the corrected row, not the raw one.
  • Extra columns in the full rstatix table. A widely used rstatix tutorial (Datanovia) shows the output carrying Mauchly’s W, the Greenhouse-Geisser epsilon (GGe) with its corrected DF and p, and the Huynh-Feldt epsilon (HFe) with its corrected DF and p. The same tutorial suggests choosing Greenhouse-Geisser when GGe is below 0.75 and Huynh-Feldt otherwise; treat that as one author’s rule of thumb, not a standard.
  • Effect size. rstatix defaults to generalized eta squared and afex lets you choose through es. State which one you report; they are not interchangeable. See effect size for ANOVA.

Post hoc comparisons

If the corrected omnibus test is significant, compare levels pairwise with a multiplicity adjustment. In rstatix the pattern used in the Datanovia tutorial is pairwise_t_test(score ~ time, paired = TRUE, p.adjust.method = "bonferroni"). Note that Tukey-style procedures are designed for between-subject designs; the Tukey in R guide explains that procedure and its assumptions.

Comparing the three routes

The three routes differ on five points that most often change a result: where the subject ID goes, how sphericity is handled, the default effect size, and what happens with multiple observations per cell. Those defaults are laid out side by side in the downloadable dataset at the end of the page, and the options table below shows where each route comes from and when it fits.

Troubleshooting

The output has the wrong degrees of freedom or an error about the ID

The ID or the within factor is probably numeric. Convert both with factor() and rerun. In long format, the number of ID levels times the number of condition levels should equal the number of rows when each subject has one observation per condition.

Data are still in wide format

All three routes expect long format. Pivot first, as in step 1; one column per time point will not work with within = time.

afex warns about aggregation

You have more than one row for at least one subject-by-condition cell. Decide deliberately whether averaging is correct (it is the afex default), then pass fun_aggregate = mean. If the extra rows are really a further factor (for example trials), model that factor instead of averaging it away.

Subjects have missing time points

The aov() manual warns that missing values will likely lose the balance, and that with two or more error strata unbalanced data are handled inefficiently; it suggests lme from the nlme package as an alternative. Mixed-effects models handle unequal numbers of observations per subject, which the assumptions guide above also discusses. Do not silently delete incomplete subjects without reporting how many were removed.

Mauchly’s test is significant

That is the situation a correction exists for. Report the Greenhouse-Geisser or Huynh-Feldt corrected values, and name the correction in the write-up.

Free alternatives and fallbacks

R itself and the packages above are free and open: aov() is part of base R, rstatix is GPL-2 licensed on CRAN, and afex and nlme are distributed through CRAN. Within R, the practical alternatives are:

Option Where it comes from When it fits
aov() with Error() Base R (stats) Balanced design, no extra packages; add your own sphericity check
rstatix::anova_test() CRAN You want Mauchly’s test and corrections in the printed table and pipe-friendly code
afex::aov_ez() CRAN Mixed designs or a default Greenhouse-Geisser correction
nlme::lme() R recommended package, as named in the aov() manual Unbalanced data or missing time points

If you work outside R, the same design is covered for SPSS (see the repeated-measures ANOVA in SPSS guide on this site) and for Python with statsmodels on this site.

Frequently asked questions

Which R package should I use for a repeated-measures ANOVA?

Use rstatix if you want Mauchly’s test and the corrections visible in the output, afex for mixed designs or when you want Greenhouse-Geisser applied by default, and base aov() with Error() only for balanced data when you will check sphericity separately.

How do I apply the Greenhouse-Geisser correction in R?

In rstatix call get_anova_table(res, correction = "GG"); in afex it is already the default and can be set with anova_table = list(correction = "GG").

Why does my ID need to be a factor?

The error strata are built from the ID. A numeric ID is treated as a continuous variable and the analysis no longer reflects the repeated-measures structure.

What if my data are unbalanced or have missing values?

The R documentation for aov() says it is designed for balanced designs and points to lme for unbalanced data with several error strata. Consider a mixed-effects model instead.

Do I need a post hoc test?

Only when the omnibus test for the within-subject factor is significant and the factor has three or more levels. Use paired comparisons with a stated multiplicity adjustment.

Sources

Data: Repeated-measures ANOVA in R: defaults of three routes (aov, rstatix, afex)

Argument conventions and defaults for running a repeated-measures ANOVA in R with base aov(), rstatix::anova_test() and afex::aov_ez(), compiled from the official reference documentation of each function.

Repeated-measures ANOVA in R: defaults of three routes (aov, rstatix, afex)
RouteSubject ID argumentSphericity handlingDefault effect sizeData requirement
aov() with Error()Error(id/time) term in the formulaNo sphericity test in summary() outputNone printedBalanced design; single Error term defines error strata
rstatix::anova_test()wid = id (unquoted column)Mauchly test shown; get_anova_table correction auto applies GG when pGeneralized eta squared (ges)Long format; Type III sums of squares for repeated measures
afex::aov_ez()id = "id" (quoted string)Greenhouse-Geisser by default; Huynh-Feldt or none selectableChosen via anova_table esLong format; several observations per cell are averaged with a warning unless fun_aggregate = mean

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about Repeated-Measures ANOVA in R: aov(), rstatix and afex

2 free questions a day, no account.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →