Skip to content

MANOVA and its four test statistics

Extend ANOVA to several outcomes, compare Pillai, Wilks, Hotelling–Lawley and Roy, and see when the choice between them matters.

Applied ~13 min9 steps

What runs in CodeSplash

You will be able to

  • Describe the hypothesis and error matrices behind MANOVA
  • Say what each of the four statistics measures and when each is strongest
  • Explain why Pillai's trace is the safe default

Read first

01

ANOVA with matrices

Read

ANOVA splits one outcome's variation into between-group and within-group sums of squares. MANOVAMANOVAANOVA for several outcomes at once — do the groups differ on the outcomes' combination? does the same for a set of outcomes, and each sum of squares becomes a matrix:

  • HH: the hypothesis matrix, variation between groups.
  • EE: the error matrix, variation within groups.

In ANOVA, F compares two numbers. Here you compare two matrices, and there is no single way to do that. The eigenvalues λi\lambda_i of E−1HE^{-1}H hold the answer: each is the ratio of between to within variation along one direction. The number of non-zero eigenvalues is limited by the number of groups and outcomes.

02

Four summaries of the same eigenvalues

Reflect
StatisticFormulaStrongest when
Pillai's tracePillai's traceSum of the explained proportions over the canonical dimensions; the most robust MANOVA statistic.∑λi/(1+λi)\sum \lambda_i / (1 + \lambda_i)Effects spread over dimensions; assumptions in doubt
Wilks' lambdaWilks' lambdaThe share of generalized variance the groups leave unexplained; small values reject.∏1/(1+λi)\prod 1 / (1 + \lambda_i)Assumptions hold; the classical report
Hotelling–Lawley traceHotelling–Lawley traceSum of the eigenvalues of E⁻¹H — powerful when the effect spreads over several dimensions.∑λi\sum \lambda_iEffects spread over dimensions; large samples
Roy's largest rootRoy's largest rootThe largest eigenvalue of E⁻¹H only — most powerful when the groups differ in one direction.λ1\lambda_1One dominant direction

Wilks is small when the effect is large; the other three grow with it. Before you read on, say which you'd report by default, and why.

03

Two groups first

Predict

Predict first

With two groups there is only one non-zero eigenvalue. What happens to the four statistics?

All four statistics give the same F and pPillai gives a smaller p than RoyThey disagree, and you must choose
Reveal

They all carry the same information. Wilks' Λ = 0.783 and Roy's root = 0.277 look different, but both give F(3, 86) = 7.95, p < .001. That is the same test as the two-sample T².

04

Three or more groups

In the app

Iris has three species and four measurements, so there are two non-zero eigenvalues and the statistics can part ways.

MANOVA (Pillai's trace)Recorded · Python and R agreeRecorded 2026-11-25 · 54 values compared
R

V = 1.19, F(8, 290) = 53.47, p < .001, partial η² = .60

V
1.192
F
53.466
df1
8
df2
290
p
< .001

Effect size

  • Multivariate partial η² 0.5959 · large

Plots

Canonical discriminant plot of SpeciesAlong which combinations of the outcomes do the groups separate, and which outcomes drive it?
View data
Specieskindlabel95% radius of the meanCan1 (r = 0.98)Can2 (r = 0.47)
setosapoint—−8.0620.3004
setosapoint—−7.129−0.7867
setosapoint—−7.490−0.2654
setosapoint—−6.813−0.6706
setosapoint—−8.1320.5145
setosapoint—−7.7021.462
setosapoint—−7.2130.3558
setosapoint—−7.605−0.0116
setosapoint—−6.561−1.015
setosapoint—−7.343−0.9473
setosapoint—−8.3970.6474
setosapoint—−7.219−0.1096
setosapoint—−7.327−1.073
setosapoint—−7.572−0.8055
setosapoint—−9.8501.586
setosapoint—−9.1582.738
setosapoint—−8.5821.834
setosapoint—−7.7810.5843
setosapoint—−8.0780.9686
setosapoint—−8.0211.141
setosapoint—−7.497−0.1884
setosapoint—−7.5861.208
setosapoint—−8.6810.8776
setosapoint—−6.2510.4397
setosapoint—−6.559−0.3892
setosapoint—−6.771−0.9706
setosapoint—−6.8230.4630
setosapoint—−7.9250.2096
setosapoint—−7.9910.0864
setosapoint—−6.829−0.5450
setosapoint—−6.759−0.7590
setosapoint—−7.3750.5658
setosapoint—−9.1261.224
setosapoint—−9.4681.825
setosapoint—−7.062−0.6634
setosapoint—−7.959−0.1650
setosapoint—−8.6140.4033
setosapoint—−8.3300.2281
setosapoint—−6.934−0.7055
setosapoint—−7.688−0.0092
setosapoint—−7.9180.6751
setosapoint—−5.662−1.934
setosapoint—−7.241−0.2726
setosapoint—−6.4141.247
setosapoint—−6.8591.052
setosapoint—−6.765−0.5052
setosapoint—−8.0820.7634
setosapoint—−7.187−0.3610
setosapoint—−8.3140.6450
setosapoint—−7.672−0.1349
versicolorpoint—1.4590.0285
versicolorpoint—1.7980.4844
versicolorpoint—2.417−0.0928
versicolorpoint—2.262−1.587
versicolorpoint—2.549−0.4722
versicolorpoint—2.430−0.9661
versicolorpoint—2.4480.7960
versicolorpoint—0.2227−1.585
versicolorpoint—1.750−0.8212
versicolorpoint—1.958−0.3516

First 60 of 157 rows.

Residual squared Mahalanobis distances against χ² quantilesAre the rows (or residuals) multivariate normal, and which rows are multivariate outliers?
View data
D² of each row
0.2911
2.031
0.5533
2.087
0.5956
1.945
1.334
0.1174
3.850
1.442
1.599
1.414
1.803
2.366
10.647
9.992
4.419
0.3669
2.533
1.470
1.055
1.007
2.286
2.769
5.282
2.403
0.8497
0.3420
0.7032
1.978
1.803
2.819
7.896
7.884
1.180
1.710
3.951
1.796
2.578
0.1432
0.5788
15.800
2.005
3.698
3.405
2.591
2.478
1.179
1.245
0.2419
5.034
1.809
3.549
2.380
2.233
2.794
3.297
5.598
2.103
3.072

First 60 of 150 rows.

Assumptions

  • Multivariate normality of residuals — Mardia skewness χ²(20) = 31.85, p = .045; kurtosis z = 3.28, p = .001; with this many residual df the tests are fairly robust.
  • Equal covariance matrices — Box's M χ²(20) = 140.94, p < .001 across 3 cells; Pillai's trace is the most robust choice.
  • Enough residual df — 147 residual df for 4 outcomes.

Multivariate tests (Type II)

TermTestStatisticApprox. Fdf1df2pPartial η²
SpeciesPillai's trace1.19253.4668290< .0010.5959
SpeciesWilks' lambda0.0234199.158288< .0010.8469
SpeciesHotelling–Lawley trace32.477580.538286< .0010.9420
SpeciesRoy's largest root32.1921166.964145< .0010.9699

Univariate follow-up ANOVAs

OutcomeTermFdf1df2pp (Holm)Partial η²
Sepal.LengthSpecies119.262147< .001< .0010.6187
Sepal.WidthSpecies49.1602147< .001< .0010.4008
Petal.LengthSpecies1180.162147< .001< .0010.9414
Petal.WidthSpecies960.012147< .001< .0010.9289

Means by Species

SpeciesnSepal.LengthSepal.WidthPetal.LengthPetal.Width
setosa505.0063.4281.4620.2460
versicolor505.9362.7704.2601.326
virginica506.5882.9745.5522.026

Canonical dimensions of Species

DimensionEigenvalueCanonical rShare of the effectStructure: Sepal.LengthStructure: Sepal.WidthStructure: Petal.LengthStructure: Petal.Width
132.1920.98480.99120.7919−0.53080.98500.9728
20.28540.47120.00880.21760.75800.04600.2229
  • Type II sums of squares and cross-products with sum-to-zero contrasts (car::Manova); F approximations as in R's summary.manova (Rao's F for Wilks). Roy's F is an upper bound, so its p-value is optimistic.
The exact R script · R R version 4.5.1 (2025-06-13)
# MANOVA / MANCOVA
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method multivariate.manova 1.0.1 · spec 0ee9390398a53f56
# Dataset: iris (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/iris.parquet", col_select = c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width", "Species")))
n_input <- nrow(df)
df[["Species"]] <- factor(df[["Species"]], levels = c("setosa", "versicolor", "virginica"))  # stored level order
df <- df[stats::complete.cases(df[c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width", "Species")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width", "Species"))  # infinite values stop the run (registry/errors.yaml)

# %% Helpers
magnitude <- function(x, cuts, labels = c("negligible", "small", "medium", "large")) {
  # Benchmark label for an effect size (rule set named in the result)
  if (is.null(x) || !is.finite(x)) return("undetermined")
  labels[findInterval(abs(x), cuts) + 1]
}

# %% Model
# car::Manova(lm(cbind(...) ~ factors + covariates), type = "II" | "III") with sum-to-zero contrasts.
outcomes <- c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width")
factor_cols <- c("Species")
covariate_cols <- c()
test <- "pillai"  # pillai | wilks | hotelling_lawley | roy
ss_type <- "II"
interactions <- TRUE && length(factor_cols) > 1
univariate <- TRUE
conf <- 0.95
alpha <- 1 - conf
Y <- as.matrix(df[outcomes])
storage.mode(Y) <- "double"
n <- nrow(Y)
dims <- ncol(Y)
factors <- lapply(factor_cols, function(f) {
  if (nlevels(df[[f]]) < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = f, min = 2, k = nlevels(df[[f]]))
  list(name = f, codes = as.integer(df[[f]]) - 1L, L = nlevels(df[[f]]))
})
for (j in seq_along(outcomes)) {
  # a constant outcome makes the residual SSCP matrix singular
  if (length(unique(Y[, j])) < 2) cs_error("CS_E_CONSTANT", column = outcomes[j])
}
covs <- lapply(covariate_cols, function(cv) list(name = cv, values = as.numeric(df[[cv]])))
fit <- cs_mv_mlm_terms(Y, factors, covs, interactions, ss_type)
E <- fit$E
df_res <- fit$df_res
NAMES <- c(pillai = "Pillai's trace", wilks = "Wilks' lambda", hotelling_lawley = "Hotelling–Lawley trace", roy = "Roy's largest root")
SYMBOL <- c(pillai = "V", wilks = "Λ", hotelling_lawley = "T", roy = "Θ")
results <- lapply(fit$terms, function(t) list(term = t, tests = cs_mv_tests(t$H, E, t$q, df_res)))
head_term <- results[[1]]$term
lead <- results[[1]]$tests[[test]]

# %% Univariate follow-ups
uni_rows <- list()
if (univariate) {
  for (r in results) {
    t <- r$term
    rows <- lapply(seq_len(dims), function(j) {
      h <- t$H[j, j]
      e <- E[j, j]
      fj <- (h / t$q) / (e / df_res)
      list(outcome = outcomes[j], term = t$name, f = fj, df1 = t$q, df2 = df_res,
           p = stats::pf(fj, t$q, df_res, lower.tail = FALSE), eta_p = h / (h + e))
    })
    holm <- cs_p_adjust(vapply(rows, function(x) x$p, 0), "holm")
    for (j in seq_along(rows)) rows[[j]]$p_holm <- holm[j]
    uni_rows <- c(uni_rows, rows)
  }
}

# %% Canonical discriminant dimensions of the first factor
can <- cs_mv_canonical(head_term$H, E, df_res, Y)
s_head <- min(dims, head_term$q)

# %% Assumptions
assumptions <- list()
X <- fit$X
resid <- qr.resid(qr(X), Y)
mardia <- if (n > dims + 1) cs_mv_mardia(resid) else NULL
if (is.null(mardia)) {
  assumptions[[1]] <- list(key = "mv_normality", label = "Multivariate normality of residuals", status = "info", detail = "Mardia's tests need more rows than outcomes + 1.")
} else {
  ok <- mardia$skew_p >= 0.05 && mardia$kurt_p >= 0.05
  status <- if (ok) "pass" else if (df_res >= 50) "info" else "warn"
  assumptions[[1]] <- list(key = "mv_normality", label = "Multivariate normality of residuals", status = status, statistic = mardia$skew, p = min(mardia$skew_p, mardia$kurt_p),
                           detail = paste0(sprintf("Mardia skewness χ²(%.0f) = %.2f, %s; kurtosis z = %.2f, %s", mardia$skew_df, mardia$skew, cs_fmt_p(mardia$skew_p), mardia$kurt_z, cs_fmt_p(mardia$kurt_p)),
                                           if (!ok) (if (status == "warn") ". Pillai's trace is the most robust statistic." else "; with this many residual df the tests are fairly robust.") else "."))
}
cells <- interaction(df[factor_cols], drop = TRUE)
cell_groups <- lapply(levels(cells), function(lv) resid[cells == lv, , drop = FALSE])
box <- if (length(cell_groups) > 1 && min(vapply(cell_groups, nrow, 0L)) > dims) cs_mv_box_m(cell_groups) else NULL
if (is.null(box)) {
  assumptions[[length(assumptions) + 1]] <- list(key = "equal_covariance", label = "Equal covariance matrices", status = "info",
                                                 detail = paste0("Box's M needs every factor cell larger than the number of outcomes; ",
                                                                 if (test == "pillai") "Pillai's trace is the safest statistic." else "prefer Pillai's trace."))
} else {
  status <- if (box$p < 0.001) "warn" else "pass"
  detail <- sprintf("Box's M χ²(%.0f) = %.2f, %s across %d cells", box$df, box$chisq, cs_fmt_p(box$p), length(cell_groups))
  detail <- paste0(detail, if (status == "warn") (if (test == "pillai") "; Pillai's trace is the most robust choice." else "; switch to Pillai's trace, the most robust statistic.") else " (judged at α = 0.001).")
  assumptions[[length(assumptions) + 1]] <- list(key = "equal_covariance", label = "Equal covariance matrices", status = status, statistic = box$chisq, p = box$p, detail = detail)
}
status <- if (df_res < dims + 5) "warn" else "pass"
assumptions[[length(assumptions) + 1]] <- list(key = "sample_size", label = "Enough residual df", status = status,
                                               detail = paste0(sprintf("%d residual df for %d outcomes", as.integer(df_res), dims), if (status == "warn") "; estimates are unstable." else "."))

# %% Result
size <- magnitude(lead$eta, c(0.01, 0.06, 0.14))
p <- lead$p
adj <- if (length(covariate_cols)) paste0(" adjusting for ", paste(covariate_cols, collapse = ", ")) else ""
kind <- if (length(covariate_cols)) "MANCOVA" else "MANOVA"
significance <- if (p < alpha) sprintf("The outcomes jointly differ across %s (%s).", head_term$name, cs_fmt_p(p)) else
  sprintf("The data are compatible with equal mean vectors across %s (%s).", head_term$name, cs_fmt_p(p))
summary <- sprintf("%s of %s%s with %s (Type %s). %s Multivariate partial η² = %.2f (%s).", kind, paste(outcomes, collapse = ", "), adj, NAMES[[test]], ss_type, significance, lead$eta, size)
if (length(results) > 1) {
  others <- vapply(results[-1], function(r) sprintf("%s (%s)", r$term$name, cs_fmt_p(r$tests[[test]]$p)), "")
  summary <- paste0(summary, " Other terms: ", paste(others, collapse = "; "), ".")
}
if (univariate) {
  n_sig <- sum(vapply(uni_rows, function(r) r$term == head_term$name && r$p_holm < alpha, logical(1)))
  summary <- paste(summary, sprintf("Univariate follow-ups: %d of %d outcomes differ across %s (Holm).", n_sig, dims, head_term$name))
}
values <- list(stat = lead$stat, f = lead$f, df1 = lead$df1, df2 = lead$df2, p = p, eta_p = lead$eta,
               n = n, dims = dims, df_res = df_res, k_terms = length(results),
               mardia_skew_p = if (is.null(mardia)) NULL else mardia$skew_p, mardia_kurt_p = if (is.null(mardia)) NULL else mardia$kurt_p,
               box_m_p = if (is.null(box)) NULL else box$p)
mv_rows <- list()
for (r in results) {
  nm <- r$term$name
  for (key in c("pillai", "wilks", "hotelling_lawley", "roy")) {
    x <- r$tests[[key]]
    values[[sprintf("%s[%s]", key, nm)]] <- x$stat
    values[[sprintf("%s_f[%s]", key, nm)]] <- x$f
    values[[sprintf("%s_df1[%s]", key, nm)]] <- x$df1
    values[[sprintf("%s_df2[%s]", key, nm)]] <- x$df2
    values[[sprintf("%s_p[%s]", key, nm)]] <- x$p
    mv_rows[[length(mv_rows) + 1]] <- list(term = nm, test = NAMES[[key]], stat = x$stat, f = x$f, df1 = x$df1, df2 = x$df2, p = x$p, eta_p = x$eta)
  }
  values[[sprintf("eta_p[%s]", nm)]] <- r$tests[[test]]$eta
}
for (r in uni_rows) {
  k <- sprintf("%s|%s", r$outcome, r$term)
  values[[sprintf("uni_f[%s]", k)]] <- r$f
  values[[sprintf("uni_p[%s]", k)]] <- r$p
  values[[sprintf("uni_p_holm[%s]", k)]] <- r$p_holm
  values[[sprintf("uni_eta_p[%s]", k)]] <- r$eta_p
}
for (i in seq_len(s_head)) values[[sprintf("can_corr[%d]", i)]] <- can$can_corr[i]
values$missing_share <- if (n_input > 0) n_dropped / n_input else 0
values$max_interaction_order <- if (interactions) length(factor_cols) else 1L
tables <- list(list(
  key = "multivariate", title = sprintf("Multivariate tests (Type %s)", ss_type),
  columns = list(list(key = "term", label = "Term", type = "string"), list(key = "test", label = "Test", type = "string"),
                 list(key = "stat", label = "Statistic", type = "number"), list(key = "f", label = "Approx. F", type = "number"),
                 list(key = "df1", label = "df1", type = "number"), list(key = "df2", label = "df2", type = "number"),
                 list(key = "p", label = "p", type = "pvalue"), list(key = "eta_p", label = "Partial η²", type = "number")),
  rows = mv_rows
))
if (univariate) {
  tables[[length(tables) + 1]] <- list(
    key = "univariate", title = "Univariate follow-up ANOVAs",
    columns = list(list(key = "outcome", label = "Outcome", type = "string"), list(key = "term", label = "Term", type = "string"),
                   list(key = "f", label = "F", type = "number"), list(key = "df1", label = "df1", type = "number"), list(key = "df2", label = "df2", type = "number"),
                   list(key = "p", label = "p", type = "pvalue"), list(key = "p_holm", label = "p (Holm)", type = "pvalue"), list(key = "eta_p", label = "Partial η²", type = "number")),
    rows = uni_rows
  )
}
f0 <- factor_cols[1]
levels0 <- levels(df[[f0]])
codes0 <- as.integer(df[[f0]]) - 1L
means_rows <- lapply(seq_along(levels0), function(i) {
  row <- list(level = levels0[i], n = sum(codes0 == i - 1L))
  for (j in seq_len(dims)) row[[sprintf("m%d", j - 1L)]] <- mean(Y[codes0 == i - 1L, j])
  row
})
tables[[length(tables) + 1]] <- list(key = "means", title = sprintf("Means by %s", f0),
                                     columns = c(list(list(key = "level", label = f0, type = "string"), list(key = "n", label = "n", type = "integer")),
                                                 lapply(seq_len(dims), function(j) list(key = sprintf("m%d", j - 1L), label = outcomes[j], type = "number"))),
                                     rows = means_rows)
tot <- sum(can$eig[seq_len(s_head)])
can_rows <- lapply(seq_len(s_head), function(i) {
  row <- list(dim = i, eig = can$eig[i], r = can$can_corr[i], share = if (tot > 0) can$eig[i] / tot else NULL)
  for (j in seq_len(dims)) row[[sprintf("s%d", j - 1L)]] <- can$structure[j, i]
  row
})
tables[[length(tables) + 1]] <- list(key = "canonical", title = sprintf("Canonical dimensions of %s", head_term$name),
                                     columns = c(list(list(key = "dim", label = "Dimension", type = "integer"), list(key = "eig", label = "Eigenvalue", type = "number"),
                                                      list(key = "r", label = "Canonical r", type = "number"), list(key = "share", label = "Share of the effect", type = "number")),
                                                 lapply(seq_len(dims), function(j) list(key = sprintf("s%d", j - 1L), label = sprintf("Structure: %s", outcomes[j]), type = "number"))),
                                     rows = can_rows)
chart_rows <- unique(round(seq(1, nrow(df), length.out = min(nrow(df), 5000))))
two <- s_head >= 2
cx <- can$scores[, 1]
cy <- if (two) can$scores[, 2] else rep(0, n)
cent_x <- vapply(seq_along(levels0), function(i) mean(cx[codes0 == i - 1L]), 0)
cent_y <- vapply(seq_along(levels0), function(i) if (two) mean(cy[codes0 == i - 1L]) else 0, 0)
cent_r <- vapply(seq_along(levels0), function(i) sqrt(stats::qchisq(conf, if (two) 2 else 1) / sum(codes0 == i - 1L)), 0)
reach <- max(1e-12, max(abs(c(cx, cy))))
sx <- can$structure[, 1]
sy <- if (two) can$structure[, 2] else rep(0, dims)
longest <- max(1e-12, max(sqrt(sx^2 + sy^2)))
scale <- 0.8 * reach / longest
np <- length(chart_rows)
nl <- length(levels0)
dist2 <- cs_mv_mahalanobis_sq(resid, E / df_res)
cs_publish(list(
  method = "multivariate.manova",
  methodVersion = "1.0.1",
  title = sprintf("%s (%s)", kind, NAMES[[test]]),
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = summary,
  apa = sprintf("%s = %s, F(%.0f, %s) = %s, %s, partial η² = %s", SYMBOL[[test]], cs_fmt_num(lead$stat), lead$df1, format(signif(lead$df2, 4)),
                cs_fmt_num(lead$f), cs_fmt_p(p), cs_fmt_num(lead$eta, leading_zero = FALSE)),
  statistics = list(list(key = "stat", label = SYMBOL[[test]], value = lead$stat), list(key = "f", label = "F", value = lead$f),
                    list(key = "df1", label = "df1", value = lead$df1), list(key = "df2", label = "df2", value = lead$df2),
                    list(key = "p", label = "p", value = p, format = "p")),
  tables = tables,
  effectSizes = list(list(key = "eta_p", label = "Multivariate partial η²", value = lead$eta,
                          method = paste0(c(pillai = "V / s", wilks = "1 − Λ^(1/s)", hotelling_lawley = "(T/s) / (1 + T/s)", roy = "Θ / (1 + Θ)")[[test]], sprintf(", s = %d", s_head)),
                          magnitude = size, ruleSet = "Cohen (1988)")),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(sprintf("Type %s sums of squares and cross-products with sum-to-zero contrasts (car::Manova); F approximations as in R's summary.manova (Rao's F for Wilks). Roy's F is an upper bound, so its p-value is optimistic.", ss_type)),
  values = values,
  charts = list(
    cs_chart("canonical", "canonical-plot", sprintf("Canonical discriminant plot of %s", head_term$name), list(
      x = cs_col(sprintf("Can1 (r = %.2f)", can$can_corr[1]), c(cx[chart_rows], cent_x, sx * scale), "numeric"),
      y = cs_col(if (two) sprintf("Can2 (r = %.2f)", can$can_corr[2]) else "(one dimension)", c(cy[chart_rows], cent_y, sy * scale), "numeric"),
      group = cs_col(f0, c(as.character(df[[f0]][chart_rows]), levels0, rep("", dims)), "categorical", levels = c(levels0, "")),
      kind = cs_col("kind", c(rep("point", np), rep("mean", nl), rep("structure", dims)), "categorical"),
      label = cs_col("label", c(rep("", np), levels0, outcomes), "categorical"),
      radius = cs_col(sprintf("%.0f%% radius of the mean", conf * 100), c(rep(NA_real_, np), cent_r, rep(NA_real_, dims)), "numeric")),
      controls = list(scale = scale)),
    cs_chart("mahalanobis", "mahalanobis-qq", "Residual squared Mahalanobis distances against χ² quantiles", list(
      d2 = cs_col("D² of each row", dist2[chart_rows], "numeric")), controls = list(df = dims))
  )
))
Python

V = 1.19, F(8, 290) = 53.47, p < .001, partial η² = .60

V
1.192
F
53.466
df1
8
df2
290
p
< .001

Effect size

  • Multivariate partial η² 0.5959 · large

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Multivariate normality of residuals — Mardia skewness χ²(20) = 31.85, p = .045; kurtosis z = 3.28, p = .001; with this many residual df the tests are fairly robust.
  • Equal covariance matrices — Box's M χ²(20) = 140.94, p < .001 across 3 cells; Pillai's trace is the most robust choice.
  • Enough residual df — 147 residual df for 4 outcomes.

Multivariate tests (Type II)

TermTestStatisticApprox. Fdf1df2pPartial η²
SpeciesPillai's trace1.19253.4668290< .0010.5959
SpeciesWilks' lambda0.0234199.158288< .0010.8469
SpeciesHotelling–Lawley trace32.477580.538286< .0010.9420
SpeciesRoy's largest root32.1921166.964145< .0010.9699

Univariate follow-up ANOVAs

OutcomeTermFdf1df2pp (Holm)Partial η²
Sepal.LengthSpecies119.262147< .001< .0010.6187
Sepal.WidthSpecies49.1602147< .001< .0010.4008
Petal.LengthSpecies1180.162147< .001< .0010.9414
Petal.WidthSpecies960.012147< .001< .0010.9289

Means by Species

SpeciesnSepal.LengthSepal.WidthPetal.LengthPetal.Width
setosa505.0063.4281.4620.2460
versicolor505.9362.7704.2601.326
virginica506.5882.9745.5522.026

Canonical dimensions of Species

DimensionEigenvalueCanonical rShare of the effectStructure: Sepal.LengthStructure: Sepal.WidthStructure: Petal.LengthStructure: Petal.Width
132.1920.98480.99120.7919−0.53080.98500.9728
20.28540.47120.00880.21760.75800.04600.2229
  • Type II sums of squares and cross-products with sum-to-zero contrasts (car::Manova); F approximations as in R's summary.manova (Rao's F for Wilks). Roy's F is an upper bound, so its p-value is optimistic.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# MANOVA / MANCOVA
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method multivariate.manova 1.0.1 · spec 0ee9390398a53f56
# Dataset: iris (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd
from scipy import stats

import codesplash as cs
from codesplash.stats import multivariate as mv
from codesplash.stats.padjust import p_adjust

# %% Data
df = pd.read_parquet("tests/parity/fixtures/iris.parquet", columns=["Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width", "Species"])
n_input = len(df)
df["Species"] = pd.Categorical(df["Species"], categories=["setosa", "versicolor", "virginica"])  # stored level order
df = df.dropna(subset=["Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width", "Species"])  # listwise deletion over the analysis columns
df["Species"] = df["Species"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width", "Species"])  # infinite values stop the run (registry/errors.yaml)

# %% Helpers
def magnitude(x, cuts, labels=("negligible", "small", "medium", "large")):
    """Benchmark label for an effect size (rule set named in the result)."""
    if x is None or not np.isfinite(x):
        return "undetermined"
    for cut, label in zip(cuts, labels):
        if abs(x) < cut:
            return label
    return labels[-1]

# %% Model
# car::Manova(lm(cbind(...) ~ factors + covariates), type = "II" | "III") with sum-to-zero contrasts.
outcomes = ["Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width"]
factor_cols = ["Species"]
covariate_cols = []
test = "pillai"  # pillai | wilks | hotelling_lawley | roy
ss_type = "II"
interactions = True and len(factor_cols) > 1
univariate = True
conf = 0.95
alpha = 1 - conf
Y = df[outcomes].to_numpy(dtype=float)
n, dims = Y.shape
factors = []
for f in factor_cols:
    L = len(df[f].cat.categories)
    if L < 2:
        cs.cs_error("CS_E_TOO_FEW_GROUPS", column=f, min=2, k=L)
    factors.append((f, df[f].cat.codes.to_numpy(), L))
for j, o in enumerate(outcomes):
    if len(np.unique(Y[:, j])) < 2:  # a constant outcome makes the residual SSCP matrix singular
        cs.cs_error("CS_E_CONSTANT", column=o)
covs = [(c, df[c].to_numpy(dtype=float)) for c in covariate_cols]
fit = mv.mlm_terms(Y, factors, covs, interactions, ss_type)
E, df_res = fit["E"], fit["df_res"]
NAMES = {"pillai": "Pillai's trace", "wilks": "Wilks' lambda", "hotelling_lawley": "Hotelling–Lawley trace", "roy": "Roy's largest root"}
SYMBOL = {"pillai": "V", "wilks": "Λ", "hotelling_lawley": "T", "roy": "Θ"}
results = []
for t in fit["terms"]:
    results.append((t, mv.mv_tests(t["H"], E, t["q"], df_res)))
head_term, head = results[0]
lead = head[test]

# %% Univariate follow-ups
uni_rows = []
if univariate:
    for t, _ in results:
        ps = []
        rows = []
        for j, o in enumerate(outcomes):
            h, e = float(t["H"][j, j]), float(E[j, j])
            fj = (h / t["q"]) / (e / df_res)
            pj = float(stats.f.sf(fj, t["q"], df_res))
            rows.append({"outcome": o, "term": t["name"], "f": fj, "df1": float(t["q"]), "df2": float(df_res), "p": pj, "eta_p": h / (h + e)})
            ps.append(pj)
        holm = p_adjust(ps, "holm")
        for r, ph in zip(rows, holm):
            r["p_holm"] = float(ph)
        uni_rows.extend(rows)

# %% Canonical discriminant dimensions of the first factor
can = mv.canonical(head_term["H"], E, df_res, Y)
s_head = min(dims, head_term["q"])

# %% Assumptions
assumptions = []
X = fit["X"]
resid = Y - X @ np.linalg.lstsq(X, Y, rcond=None)[0]
mardia = mv.mardia(resid) if n > dims + 1 else None
if mardia is None:
    assumptions.append({"key": "mv_normality", "label": "Multivariate normality of residuals", "status": "info", "detail": "Mardia's tests need more rows than outcomes + 1."})
else:
    ok = mardia["skew_p"] >= 0.05 and mardia["kurt_p"] >= 0.05
    status = "pass" if ok else ("info" if df_res >= 50 else "warn")
    assumptions.append({"key": "mv_normality", "label": "Multivariate normality of residuals", "status": status, "statistic": mardia["skew"], "p": min(mardia["skew_p"], mardia["kurt_p"]),
                        "detail": f"Mardia skewness χ²({mardia['skew_df']:.0f}) = {mardia['skew']:.2f}, {cs.fmt_p(mardia['skew_p'])}; kurtosis z = {mardia['kurt_z']:.2f}, {cs.fmt_p(mardia['kurt_p'])}"
                                  + ((". Pillai's trace is the most robust statistic." if status == "warn" else "; with this many residual df the tests are fairly robust.") if not ok else ".")})
cells = pd.Series(list(zip(*[df[f].astype(str) for f in factor_cols]))) if factor_cols else pd.Series(["all"] * n)
cell_codes = cells.astype("category").cat.codes.to_numpy()
cell_groups = [resid[cell_codes == c] for c in range(cell_codes.max() + 1)]
box = mv.box_m(cell_groups) if len(cell_groups) > 1 and min(g.shape[0] for g in cell_groups) > dims else None
if box is None:
    assumptions.append({"key": "equal_covariance", "label": "Equal covariance matrices", "status": "info",
                        "detail": "Box's M needs every factor cell larger than the number of outcomes; " + ("Pillai's trace is the safest statistic." if test == "pillai" else "prefer Pillai's trace.")})
else:
    status = "warn" if box["p"] < 0.001 else "pass"
    detail = f"Box's M χ²({box['df']:.0f}) = {box['chisq']:.2f}, {cs.fmt_p(box['p'])} across {len(cell_groups)} cells"
    if status == "warn":
        detail += "; Pillai's trace is the most robust choice." if test == "pillai" else "; switch to Pillai's trace, the most robust statistic."
    else:
        detail += " (judged at α = 0.001)."
    assumptions.append({"key": "equal_covariance", "label": "Equal covariance matrices", "status": status, "statistic": box["chisq"], "p": box["p"], "detail": detail})
status = "warn" if df_res < dims + 5 else "pass"
assumptions.append({"key": "sample_size", "label": "Enough residual df", "status": status,
                    "detail": f"{df_res} residual df for {dims} outcomes" + ("; estimates are unstable." if status == "warn" else ".")})

# %% Result
size = magnitude(lead["eta"], (0.01, 0.06, 0.14))
p = lead["p"]
adj = f" adjusting for {', '.join(covariate_cols)}" if covariate_cols else ""
kind = "MANCOVA" if covariate_cols else "MANOVA"
significance = (f"The outcomes jointly differ across {head_term['name']} ({cs.fmt_p(p)})." if p < alpha
                else f"The data are compatible with equal mean vectors across {head_term['name']} ({cs.fmt_p(p)}).")
summary = f"{kind} of {', '.join(outcomes)}{adj} with {NAMES[test]} (Type {ss_type}). {significance} Multivariate partial η² = {lead['eta']:.2f} ({size})."
others = [f"{t['name']} ({cs.fmt_p(r[test]['p'])})" for t, r in results[1:]]
if others:
    summary += " Other terms: " + "; ".join(others) + "."
if univariate:
    sig_uni = [r["outcome"] for r in uni_rows if r["term"] == head_term["name"] and r["p_holm"] < alpha]
    summary += f" Univariate follow-ups: {len(sig_uni)} of {dims} outcomes differ across {head_term['name']} (Holm)."
values = {"stat": lead["stat"], "f": lead["f"], "df1": lead["df1"], "df2": lead["df2"], "p": p, "eta_p": lead["eta"],
          "n": n, "dims": dims, "df_res": float(df_res), "k_terms": len(results),
          "mardia_skew_p": None if mardia is None else mardia["skew_p"], "mardia_kurt_p": None if mardia is None else mardia["kurt_p"],
          "box_m_p": None if box is None else box["p"]}
mv_rows = []
for t, r in results:
    for key in ("pillai", "wilks", "hotelling_lawley", "roy"):
        x = r[key]
        values[f"{key}[{t['name']}]"] = x["stat"]
        values[f"{key}_f[{t['name']}]"] = x["f"]
        values[f"{key}_df1[{t['name']}]"] = x["df1"]
        values[f"{key}_df2[{t['name']}]"] = x["df2"]
        values[f"{key}_p[{t['name']}]"] = x["p"]
        mv_rows.append({"term": t["name"], "test": NAMES[key], "stat": x["stat"], "f": x["f"], "df1": x["df1"], "df2": x["df2"], "p": x["p"], "eta_p": x["eta"]})
    values[f"eta_p[{t['name']}]"] = r[test]["eta"]
for r in uni_rows:
    k = f"{r['outcome']}|{r['term']}"
    values[f"uni_f[{k}]"] = r["f"]
    values[f"uni_p[{k}]"] = r["p"]
    values[f"uni_p_holm[{k}]"] = r["p_holm"]
    values[f"uni_eta_p[{k}]"] = r["eta_p"]
for i in range(s_head):
    values[f"can_corr[{i + 1}]"] = float(can["can_corr"][i])
values["missing_share"] = n_dropped / n_input if n_input else 0.0
values["max_interaction_order"] = len(factor_cols) if interactions else 1
tables = [{
    "key": "multivariate", "title": f"Multivariate tests (Type {ss_type})",
    "columns": [{"key": "term", "label": "Term", "type": "string"}, {"key": "test", "label": "Test", "type": "string"},
                {"key": "stat", "label": "Statistic", "type": "number"}, {"key": "f", "label": "Approx. F", "type": "number"},
                {"key": "df1", "label": "df1", "type": "number"}, {"key": "df2", "label": "df2", "type": "number"},
                {"key": "p", "label": "p", "type": "pvalue"}, {"key": "eta_p", "label": "Partial η²", "type": "number"}],
    "rows": mv_rows,
}]
if univariate:
    tables.append({
        "key": "univariate", "title": "Univariate follow-up ANOVAs",
        "columns": [{"key": "outcome", "label": "Outcome", "type": "string"}, {"key": "term", "label": "Term", "type": "string"},
                    {"key": "f", "label": "F", "type": "number"}, {"key": "df1", "label": "df1", "type": "number"}, {"key": "df2", "label": "df2", "type": "number"},
                    {"key": "p", "label": "p", "type": "pvalue"}, {"key": "p_holm", "label": "p (Holm)", "type": "pvalue"}, {"key": "eta_p", "label": "Partial η²", "type": "number"}],
        "rows": uni_rows,
    })
f0 = factor_cols[0]
levels0 = [str(lv) for lv in df[f0].cat.categories]
codes0 = df[f0].cat.codes.to_numpy()
means_rows = []
for i, lv in enumerate(levels0):
    row = {"level": lv, "n": int((codes0 == i).sum())}
    for j, o in enumerate(outcomes):
        row[f"m{j}"] = float(Y[codes0 == i, j].mean())
    means_rows.append(row)
tables.append({"key": "means", "title": f"Means by {f0}",
               "columns": [{"key": "level", "label": f0, "type": "string"}, {"key": "n", "label": "n", "type": "integer"}]
               + [{"key": f"m{j}", "label": o, "type": "number"} for j, o in enumerate(outcomes)],
               "rows": means_rows})
tables.append({"key": "canonical", "title": f"Canonical dimensions of {head_term['name']}",
               "columns": [{"key": "dim", "label": "Dimension", "type": "integer"}, {"key": "eig", "label": "Eigenvalue", "type": "number"},
                           {"key": "r", "label": "Canonical r", "type": "number"}, {"key": "share", "label": "Share of the effect", "type": "number"}]
               + [{"key": f"s{j}", "label": f"Structure: {o}", "type": "number"} for j, o in enumerate(outcomes)],
               "rows": [dict({"dim": i + 1, "eig": float(can["eig"][i]), "r": float(can["can_corr"][i]),
                              "share": float(can["eig"][i] / can["eig"][:s_head].sum()) if can["eig"][:s_head].sum() > 0 else None},
                             **{f"s{j}": float(can["structure"][j, i]) for j in range(dims)}) for i in range(s_head)]})
chart_rows = np.unique(np.round(np.linspace(0, len(df) - 1, min(len(df), 5000))).astype(int))
two = s_head >= 2
cx, cy = can["scores"][:, 0], (can["scores"][:, 1] if two else np.zeros(n))
centroids = [(lv, float(cx[codes0 == i].mean()), float(cy[codes0 == i].mean()) if two else 0.0, float(np.sqrt(stats.chi2.ppf(conf, 2 if two else 1) / (codes0 == i).sum())))
             for i, lv in enumerate(levels0)]
reach = max(1e-12, float(np.max(np.abs(np.concatenate([cx, cy])))))
longest = max(1e-12, float(np.max(np.hypot(can["structure"][:, 0], can["structure"][:, 1] if two else 0))))
scale = 0.8 * reach / longest
kind_col = ["point"] * len(chart_rows) + ["mean"] * len(levels0) + ["structure"] * dims
can_x = list(cx[chart_rows]) + [c[1] for c in centroids] + list(can["structure"][:, 0] * scale)
can_y = list(cy[chart_rows]) + [c[2] for c in centroids] + list((can["structure"][:, 1] if two else np.zeros(dims)) * scale)
can_g = list(df[f0].astype(str).to_numpy()[chart_rows]) + levels0 + [""] * dims
can_l = [""] * len(chart_rows) + levels0 + outcomes
can_r = [None] * len(chart_rows) + [c[3] for c in centroids] + [None] * dims
dist2 = mv.mahalanobis_sq(resid, E / df_res)
cs.publish({
    "method": "multivariate.manova",
    "methodVersion": "1.0.1",
    "title": f"{kind} ({NAMES[test]})",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "apa": f"{SYMBOL[test]} = {cs.fmt_num(lead['stat'])}, F({lead['df1']:.0f}, {lead['df2']:.4g}) = {cs.fmt_num(lead['f'])}, {cs.fmt_p(p)}, partial η² = {cs.fmt_num(lead['eta'], leading_zero=False)}",
    "statistics": [{"key": "stat", "label": SYMBOL[test], "value": lead["stat"]}, {"key": "f", "label": "F", "value": lead["f"]},
                   {"key": "df1", "label": "df1", "value": lead["df1"]}, {"key": "df2", "label": "df2", "value": lead["df2"]},
                   {"key": "p", "label": "p", "value": p, "format": "p"}],
    "tables": tables,
    "effectSizes": [{"key": "eta_p", "label": "Multivariate partial η²", "value": lead["eta"],
                     "method": {"pillai": "V / s", "wilks": "1 − Λ^(1/s)", "hotelling_lawley": "(T/s) / (1 + T/s)", "roy": "Θ / (1 + Θ)"}[test] + f", s = {s_head}",
                     "magnitude": size, "ruleSet": "Cohen (1988)"}],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Type {ss_type} sums of squares and cross-products with sum-to-zero contrasts (car::Manova); F approximations as in R's summary.manova (Rao's F for Wilks). Roy's F is an upper bound, so its p-value is optimistic."],
    "values": values,
    "charts": [
        cs.chart("canonical", "canonical-plot", f"Canonical discriminant plot of {head_term['name']}", {
            "x": cs.col(f"Can1 (r = {can['can_corr'][0]:.2f})", can_x, "numeric"),
            "y": cs.col(f"Can2 (r = {can['can_corr'][1]:.2f})" if two else "(one dimension)", can_y, "numeric"),
            "group": cs.col(f0, can_g, "categorical", levels=levels0 + [""]),
            "kind": cs.col("kind", kind_col, "categorical"),
            "label": cs.col("label", can_l, "categorical"),
            "radius": cs.col(f"{conf:.0%} radius of the mean", can_r, "numeric")}, controls={"scale": scale}),
        cs.chart("mahalanobis", "mahalanobis-qq", "Residual squared Mahalanobis distances against χ² quantiles", {
            "d2": cs.col("D² of each row", dist2[chart_rows], "numeric")}, controls={"df": dims}),
    ],
})

Pillai's V = 1.19, F(8, 290) = 53.5, p < .001. Partial η2\eta^2 = 0.60.

The Multivariate tests table lists all four, whichever one leads. Compare their approximate F values, then the Canonical dimensions table. What share of the effect lies in the first dimension?

05

Why Pillai by default

Read

Roy's statistic looks at only the best direction, and that direction was chosen from the data. Its F is an upper bound, so its p-value is too small when more than one eigenvalue is non-zero.

Olson (1974) simulated the four under unequal covariances and non-normal data, and Pillai's trace kept its error rate best. CodeSplash makes it the default.

Here the assumption is in real doubt: Box's M gives p < .001.

On the pottery data, the Hotelling–Lawley trace is 35.4. With so few rows per site, read the assumption rows before you trust a huge F.

06

Spot the misuse

Predict

Predict first

A colleague runs MANOVA on three groups. Pillai's p sits above 0.05 and Roy's sits below it, so they report Roy.

Is that defensible?

Reasonable: all four are validNot defensible: it inflates your false-positive rateFine if you report Roy's F as an upper bound
Reveal

Not defensible. Choosing the statistic after seeing the p-values is a forking path, and Roy's p is the optimistic one. Pick the statistic before you look, and report the choice.

07

Check your understanding

Checkpoint

Check yourself

A MANOVA has a single non-zero eigenvalue, λ=3\lambda = 3. What is Wilks' lambda?

Show the answer

Answer: 0.25

Λ=1/(1+3)=0.25\Lambda = 1 / (1 + 3) = 0.25. Wilks is the share of generalized variance left unexplained.

Check yourself

Same eigenvalue, λ=3\lambda = 3. What is Pillai's trace?

Show the answer

Answer: 0.75

V=3/(1+3)=0.75V = 3 / (1 + 3) = 0.75. With one eigenvalue, Pillai is the explained share and Wilks is the rest, so they add up to 1.

Check yourself

Four groups, similar sizes, and Box's M is small. Which statistic should lead?

Show the answer

Answer: a

Pillai holds its error rate best when covariances differ, especially with similar group sizes. Roy's F is an upper bound.

08

Do it in CodeSplash

In the app

Choose your Outcomes and Factors. Test statistic sets which one leads the result and the narrative.

Python
import pandas as pd
from statsmodels.multivariate.manova import MANOVA

df = pd.read_csv("iris.csv")
df.columns = ["sl", "sw", "pl", "pw", "species"]
print(MANOVA.from_formula("sl + sw + pl + pw ~ species", data=df).mv_test())
R
fit <- manova(
  cbind(Sepal.Length, Sepal.Width, Petal.Length, Petal.Width) ~ Species,
  data = iris
)
summary(fit, test = "Pillai")
summary(fit, test = "Wilks")
09

Recap

Recap
  • MANOVA compares a between-group matrix with a within-group matrix through its eigenvalues.
  • With two groups, all four statistics agree. With more, they can differ.
  • Pillai's trace is the robust default, and Roy's F is an upper bound.
  • Choose the statistic before you see the results.

Concepts in this lesson