Skip to content

BMultivariate · multivariate.manova

MANOVA / MANCOVA

Do several outcomes jointly differ across groups (adjusting for covariates)?

Multivariate analysis of (co)variance: Pillai's trace, Wilks' lambda, the Hotelling–Lawley trace and Roy's largest root for every factor, interaction and covariate (Type II or III sums of squares and products), multivariate partial η², univariate follow-up ANOVAs with Holm-adjusted p, canonical discriminant dimensions, and checks of multivariate normality (Mardia) and equal covariances (Box's M).

Verified in Python and R Python and R agree to 10 decimals Also called MANOVA, MANCOVA, multivariate analysis of variance…

A real result

Example “Wilks guide”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

MANOVA (Wilks' lambda)Recorded · Python and R agreeRecorded 2026-11-25 · 49 values compared
R

Λ = 0.78, F(3, 86) = 7.95, p < .001, partial η² = .22

Λ
0.7829
F
7.948
df1
3
df2
86
p
< .001

Effect size

  • Multivariate partial η² 0.2171 · large

Plots

Canonical discriminant plot of groupAlong which combinations of the outcomes do the groups separate, and which outcomes drive it?
View data
groupkindlabel95% radius of the meanCan1 (r = 0.47)(one dimension)
g1point—−1.3030
g1point—−0.05900
g1point—−1.6250
g1point—−0.85560
g1point—−1.5310
g1point—−0.93860
g1point—−0.44480
g1point—−1.7630
g1point—0.72630
g1point—0.49970
g1point—−2.3290
g1point—−0.52310
g1point—−1.4310
g1point—0.13970
g1point—−3.5100
g1point—0.34480
g1point—−1.2100
g1point—−1.1270
g1point—−1.3360
g1point—−0.46040
g1point—−0.27410
g1point—−0.59890
g1point—−1.6860
g1point—0.05640
g1point—−1.2320
g1point—1.0620
g1point—−1.0160
g1point—1.0610
g1point—−1.1020
g1point—0.59470
g1point—−1.0030
g1point—−0.74160
g1point—0.24620
g1point—−0.55530
g1point—−0.22200
g1point—−0.30960
g1point—1.4770
g1point—−0.11560
g1point—0.68530
g1point—−0.87540
g2point—1.3430
g2point—0.27440
g2point—0.75750
g2point—0.18340
g2point—−1.2190
g2point—1.0670
g2point—−1.8220
g2point—−0.03030
g2point—1.8600
g2point—1.2060
g2point—−0.53250
g2point—3.2660
g2point—0.99000
g2point—0.88770
g2point—0.42570
g2point—0.82020
g2point—−0.50850
g2point—1.2590
g2point—1.3080
g2point—0.76700

First 60 of 95 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
2.013
3.910
1.980
2.447
1.273
8.630
1.132
1.693
2.447
6.425
4.314
3.150
0.8975
1.411
11.042
2.201
1.977
0.8316
1.688
1.697
1.913
0.2725
2.192
3.363
4.986
4.965
6.749
3.958
1.901
4.762
2.764
1.226
2.698
1.305
0.9415
2.097
7.354
2.608
6.619
2.620
3.338
10.079
1.111
1.338
4.689
1.301
6.291
0.9918
2.466
1.261
1.262
9.729
0.3846
0.8933
0.4656
0.6266
9.858
0.6737
0.8701
5.414

First 60 of 90 rows.

Assumptions

  • Multivariate normality of residuals — Mardia skewness χ²(10) = 6.91, p = .734; kurtosis z = 0.20, p = .845.
  • Equal covariance matrices — Box's M χ²(6) = 5.64, p = .464 across 2 cells (judged at α = 0.001).
  • Enough residual df — 88 residual df for 3 outcomes.

Multivariate tests (Type II)

TermTestStatisticApprox. Fdf1df2pPartial η²
groupPillai's trace0.21717.948386< .0010.2171
groupWilks' lambda0.78297.948386< .0010.2171
groupHotelling–Lawley trace0.27737.948386< .0010.2171
groupRoy's largest root0.27737.948386< .0010.2171

Univariate follow-up ANOVAs

OutcomeTermFdf1df2pp (Holm)Partial η²
y1group7.521188.007.0150.0787
y2group9.130188.003.0100.0940
y3group5.370188.023.0230.0575

Means by group

groupny1y2y3
g140−0.0414−0.1295−0.1403
g2500.50740.47300.3592

Canonical dimensions of group

DimensionEigenvalueCanonical rShare of the effectStructure: y1Structure: y2Structure: y3
10.27730.465910.60230.65810.5147
  • 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.
Python

Λ = 0.78, F(3, 86) = 7.95, p < .001, partial η² = .22

Λ
0.7829
F
7.948
df1
3
df2
86
p
< .001

Effect size

  • Multivariate partial η² 0.2171 · large

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

Assumptions

  • Multivariate normality of residuals — Mardia skewness χ²(10) = 6.91, p = .734; kurtosis z = 0.20, p = .845.
  • Equal covariance matrices — Box's M χ²(6) = 5.64, p = .464 across 2 cells (judged at α = 0.001).
  • Enough residual df — 88 residual df for 3 outcomes.

Multivariate tests (Type II)

TermTestStatisticApprox. Fdf1df2pPartial η²
groupPillai's trace0.21717.948386< .0010.2171
groupWilks' lambda0.78297.948386< .0010.2171
groupHotelling–Lawley trace0.27737.948386< .0010.2171
groupRoy's largest root0.27737.948386< .0010.2171

Univariate follow-up ANOVAs

OutcomeTermFdf1df2pp (Holm)Partial η²
y1group7.521188.007.0150.0787
y2group9.130188.003.0100.0940
y3group5.370188.023.0230.0575

Means by group

groupny1y2y3
g140−0.0414−0.1295−0.1403
g2500.50740.47300.3592

Canonical dimensions of group

DimensionEigenvalueCanonical rShare of the effectStructure: y1Structure: y2Structure: y3
10.27730.465910.60230.65810.5147
  • 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.

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Wilks guidemv_guide · factors: group · outcomes: y1, y2, y3
  • Roy guidemv_guide · factors: group · outcomes: y1, y2, y3
  • Mancova baumannmv_baumann · covariates: pretest1, pretest2 · factors: group · outcomes: post1, post2, post3
  • Pottery hotelling lawleymv_pottery · factors: Site · outcomes: Al, Fe, Mg, Ca, Na
  • Factorial type3mv_obrienkaiser · factors: treatment, gender · outcomes: post_1, post_2, post_3, post_4, post_5
  • Factorial type2 no interactionmv_obrienkaiser · factors: treatment, gender · outcomes: post_1, post_2, post_3
  • Iris pillaiiris · factors: Species · outcomes: Sepal.Length, Sepal.Width, Petal.Length, Petal.Width
  • Degenerate constantmv_guide · factors: group · outcomes: y1, y2, y3

In the guides

Tests from the statistics guide this method runs

Where it sits in the decision guides

  • Factorial designs, covariates, multivariate (ANCOVA, MANOVA) · Statistics Guide · B — Compare groups

What you need

Outcomesnumeric · 2–20 columns
Two or more numeric outcomes analyzed jointly (their correlations are used, so do not pick near-duplicates).
Factorscategorical / boolean · 1–3 columns · 2–30 levels
One to three grouping factors; with two or more you can include their interactions.
Covariatesnumeric · 0–10 columns
Optional numeric covariates to adjust for (MANCOVA); each also gets its own multivariate test.

Choices you make

hypothesis

Test statisticdefault pillai

Which statistic leads the result and the narrative (all four are always reported). Pillai's trace is the safest default.

  • Pillai's trace(default) — Sum of the explained proportions over all canonical dimensions; the most robust to unequal covariances and non-normality (Olson 1974).
  • Wilks' lambda — Unexplained generalized variance |E| / |E + H|; small values reject. F by Rao's approximation (exact for 1–2 dimensions).
  • Hotelling–Lawley trace — Sum of the eigenvalues of E⁻¹H; powerful when the effect spreads over several dimensions.
  • Roy's largest root — The largest eigenvalue only — most powerful when the effect lies in one direction; its F is an upper bound, so the p-value is optimistic.
Confidence leveldefault 0.95

Significance is judged at α = 1 − confidence level.

statistics

Sums of squaresdefault II

How each term's hypothesis matrix is adjusted for the others; Types II and III agree for one factor and for balanced designs.

  • Type II(default) — Each term adjusted for every term that does not contain it (marginality); the usual choice without important interactions.
  • Type III — Each term adjusted for all others, interactions included (sum-to-zero coding); matches SPSS/SAS defaults for unbalanced designs.
Include interactionsdefault on

Model every interaction among the factors (needs at least one row in every combination).

posthoc

Univariate follow-up ANOVAsdefault on

An F test for each outcome and term (same sums of squares) with Holm-adjusted p within each term.

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • Multivariate normality of residuals

    Mardia's skewness and kurtosis tests of the model residuals.

  • Equal covariance matrices

    Box's M on the residuals of each factor cell at α = 0.001; Pillai's trace is robust to moderate violations with similar cell sizes.

    • If violated → Use Pillai's trace — Pillai's trace keeps its Type I error best when covariance matrices differ, especially with similar cell sizes. Changes the question: None — the same multivariate hypothesis with the most robust statistic.
  • Enough residual df

    Residual degrees of freedom should comfortably exceed the number of outcomes.

What it reports

  • Tests: Joint difference across the first factor
stat
A single number that summarizes how far your data are from what H₀ predicts.
f
The ratio of explained to unexplained variance, used by ANOVA and regression tests.
df1
How much independent information is left to estimate variability after fitting the model.
df2
How much independent information is left to estimate variability after fitting the model.
p
How surprising your data would be if the null hypothesis were true, as a probability.
eta_p
How surprising your data would be if the null hypothesis were true, as a probability.
n
How many independent units the analysis used; it sets precision and power.
dims
How many outcome columns a multivariate test compares at once. More of them need more rows per group.
df_res
How much independent information is left to estimate variability after fitting the model.
k_terms
How many coefficients the model estimated, counting the intercept.
mardia_skew_p
Multivariate skewness and kurtosis tests of whether rows (or residuals) are multivariate normal.
mardia_kurt_p
Multivariate skewness and kurtosis tests of whether rows (or residuals) are multivariate normal.
box_m_p
Tests whether groups share one covariance matrix, by comparing their log-determinants.
missing_share
Values that were not recorded; how they went missing decides which fixes are safe.
max_interaction_order
The most factors combined in one term of the model: 1 means main effects only, 2 two-way interactions.

Per group, level or term: pillai[<term>], pillai_f[<term>], pillai_df1[<term>], pillai_df2[<term>], pillai_p[<term>], wilks[<term>], wilks_f[<term>], wilks_df1[<term>], wilks_df2[<term>], wilks_p[<term>], hotelling_lawley[<term>], hotelling_lawley_f[<term>], hotelling_lawley_df1[<term>], hotelling_lawley_df2[<term>], hotelling_lawley_p[<term>], roy[<term>], roy_f[<term>], roy_df1[<term>], roy_df2[<term>], roy_p[<term>], eta_p[<term>], uni_f[<outcome>|<term>], uni_p[<outcome>|<term>], uni_p_holm[<outcome>|<term>], uni_eta_p[<outcome>|<term>], can_corr[<dimension>]

Python and R

Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.

Default traps between the two languages

  • Roy's largest-root F is the usual upper bound (summary.manova, car::Manova, SAS, SPSS); its p-value is optimistic when more than one root is non-zero.
Python

The exact script CodeSplash ran for example “Wilks guide” · 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 b4143755ffb6fd2b
# Dataset: mv_guide (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/mv_guide.parquet", columns=["y1", "y2", "y3", "group"])
n_input = len(df)
df["group"] = pd.Categorical(df["group"], categories=["g1", "g2"])  # stored level order
df = df.dropna(subset=["y1", "y2", "y3", "group"])  # listwise deletion over the analysis columns
df["group"] = df["group"].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, ["y1", "y2", "y3", "group"])  # 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 = ["y1", "y2", "y3"]
factor_cols = ["group"]
covariate_cols = []
test = "wilks"  # 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}),
    ],
})
R

The exact script CodeSplash ran for example “Wilks guide” · 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 b4143755ffb6fd2b
# Dataset: mv_guide (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/mv_guide.parquet", col_select = c("y1", "y2", "y3", "group")))
n_input <- nrow(df)
df[["group"]] <- factor(df[["group"]], levels = c("g1", "g2"))  # stored level order
df <- df[stats::complete.cases(df[c("y1", "y2", "y3", "group")]), , 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("y1", "y2", "y3", "group"))  # 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("y1", "y2", "y3")
factor_cols <- c("group")
covariate_cols <- c()
test <- "wilks"  # 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))
  )
))

Sources

  • Pillai, K. C. S. (1955). Some new test criteria in multivariate analysis. Annals of Mathematical Statistics, 26, 117–121.
  • Wilks, S. S. (1932). Certain generalizations in the analysis of variance. Biometrika, 24, 471–494.
  • Rao, C. R. (1951). An asymptotic expansion of the distribution of Wilks' criterion. Bulletin of the International Statistical Institute, 33, 177–180.
  • Olson, C. L. (1974). Comparative robustness of six tests in multivariate analysis of variance. Journal of the American Statistical Association, 69, 894–908.
  • Fox, J., & Weisberg, S. (2019). An R Companion to Applied Regression (3rd ed.), §9.4 (Type II and III MANOVA). Sage.

From the CodeSplash method registry · multivariate.manova v1.0.1.