Skip to content

BMultivariate · multivariate.permanova

PERMANOVA (permutational MANOVA)

Do groups differ in their multivariate profile, judged by a dissimilarity between rows?

PERMANOVA partitions the squared dissimilarities between rows into between- and within-group parts and tests the pseudo-F by permuting group labels — MANOVA for any dissimilarity, without assuming normality. It is always reported with PERMDISP, because PERMANOVA also reacts to groups that differ only in spread, plus optional Holm-adjusted pairwise tests and a principal-coordinates plot.

Verified in Python and R Python and R agree to 6 decimals Seeded Also called PERMANOVA, permutational MANOVA, adonis…

A real result

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

PERMANOVARecorded · Python and R agreeRecorded 2026-11-17 · 17 values compared
R

PERMANOVA (Euclidean), pseudo-F(1, 88) = 7.24, R² = 0.08, p = .005

Pseudo-F
7.236
df1
1
df2
88
R²
0.0760
p
.005

Effect size

  • R² 0.0760

Plots

Principal coordinates of the Euclidean dissimilarities by groupDo the groups separate in the dissimilarity space, and do they differ in where they sit or in how spread out they are?
View data
groupPCoA 1 (42.4%)PCoA 2 (32.5%)
g11.880−0.0590
g1−1.6120.8910
g11.8520.2849
g11.1820.9049
g10.65580.7322
g1−1.7232.557
g1−0.35371.066
g10.87331.373
g1−1.190−0.0974
g1−1.994−0.0357
g12.3631.065
g1−0.91710.3980
g11.1050.4423
g1−0.87310.2165
g11.6093.095
g10.7412−0.9501
g11.794−0.2277
g11.2020.0360
g10.81361.379
g10.6387−0.6940
g1−0.69970.1242
g10.44240.5991
g10.28181.578
g11.449−0.7876
g10.5212−0.4453
g10.2217−1.750
g12.778−1.161
g1−1.653−0.0826
g11.813−0.1413
g11.168−0.9665
g10.91671.327
g11.1300.4960
g1−0.41980.8517
g10.3646−0.3902
g10.48880.4014
g11.132−0.9397
g1−0.82840.1889
g1−1.2680.8131
g1−1.258−1.108
g10.39731.515
g20.3005−1.929
g22.515−1.324
g2−0.27580.0576
g20.8521−0.7303
g2−0.25711.649
g2−1.075−0.8621
g21.3360.2787
g20.19760.4148
g2−1.410−0.4676
g2−0.5506−1.262
g20.4851−0.0900
g2−0.9148−2.405
g2−0.6339−0.7328
g2−1.1240.1816
g20.1908−0.2489
g2−1.143−0.1104
g20.49091.963
g2−0.9839−0.6186
g2−0.5787−1.013
g2−1.271−1.232

First 60 of 90 rows.

Assumptions

  • Similar spread across groups (PERMDISP) — PERMDISP F(1, 88) = 2.377, permutation p = .100.
  • Exchangeable rows — Labels were permuted freely; for blocks, sites or repeated measures add them as strata so permutations respect the design.

PERMANOVA table

SourcedfSum of squaresR²Pseudo-Fp
group120.3040.07607.236.005
Residual88246.920.9240——
Total89267.221——

Dispersion: distance to each group's spatial median (PERMDISP)

groupnMean distance to center
g1401.642
g2501.425

Reading PERMANOVA with PERMDISP

TestFpWhat it says
PERMANOVA (location and spread)7.236.005Groups differ
PERMDISP (spread only)2.377.100Spreads similar
Conclusion——The groups differ in where they sit (their centers), and their spreads are similar, so PERMANOVA's result is about location.
  • Euclidean dissimilarity of the variables; p from 199 label permutations on the shared seeded stream (seed 42), (1 + #F* ≥ F) / (B + 1).
  • PERMDISP is reported with PERMANOVA because PERMANOVA is sensitive to differences in spread as well as location.
Python

PERMANOVA (Euclidean), pseudo-F(1, 88) = 7.24, R² = 0.08, p = .005

Pseudo-F
7.236
df1
1
df2
88
R²
0.0760
p
.005

Effect size

  • R² 0.0760

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

Assumptions

  • Similar spread across groups (PERMDISP) — PERMDISP F(1, 88) = 2.377, permutation p = .100.
  • Exchangeable rows — Labels were permuted freely; for blocks, sites or repeated measures add them as strata so permutations respect the design.

PERMANOVA table

SourcedfSum of squaresR²Pseudo-Fp
group120.3040.07607.236.005
Residual88246.920.9240——
Total89267.221——

Dispersion: distance to each group's spatial median (PERMDISP)

groupnMean distance to center
g1401.642
g2501.425

Reading PERMANOVA with PERMDISP

TestFpWhat it says
PERMANOVA (location and spread)7.236.005Groups differ
PERMDISP (spread only)2.377.100Spreads similar
Conclusion——The groups differ in where they sit (their centers), and their spreads are similar, so PERMANOVA's result is about location.
  • Euclidean dissimilarity of the variables; p from 199 label permutations on the shared seeded stream (seed 42), (1 + #F* ≥ F) / (B + 1).
  • PERMDISP is reported with PERMANOVA because PERMANOVA is sensitive to differences in spread as well as location.

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

  • Guide euclideanmv_guide · group: group · variables: y1, y2, y3
  • Dune bray managementmv_dune · group: Management · variables: Achimill, Agrostol, Airaprae, Alopgeni, Anthodor, Bellpere, Bromhord, Chenalbu, Cirsarve, Comapalu, Eleopalu, Elymrepe, Empenigr, Hyporadi, Juncarti, Juncbufo, Lolipere, Planlanc, Poaprat, Poatriv, Ranuflam, Rumeacet, Sagiproc, Salirepe, Scorautu, Trifprat, Trifrepe, Vicilath, Bracruta, Callcusp
  • Dune hellinger centroid stratamv_dune · group: Use · strata: Moisture · variables: Achimill, Agrostol, Alopgeni, Bellpere, Elymrepe, Lolipere, Planlanc, Poaprat, Poatriv, Rumeacet, Scorautu, Trifrepe
  • Iris gower no pairsiris · group: Species · variables: Sepal.Length, Sepal.Width, Petal.Length, Petal.Width
  • Degenerate single levelmv_guide · group: group · variables: y1, y2, y3

In the guides

Tests from the statistics guide this method runs

Where it sits in the decision guides

  • More than two independent groups: one-way ANOVA, Kruskal–Wallis · Statistics Guide · B — Compare groups
  • Factorial designs, covariates, multivariate (ANCOVA, MANOVA) · Statistics Guide · B — Compare groups

What you need

Variablesnumeric · 1–200 columns
The numeric variables (or species counts) whose dissimilarities are compared.
Groupscategorical / boolean · 1 column · 2–30 levels
The groups to compare.
Strata (optional)categorical · 0–1 column
Blocks or sites within which labels are permuted, so permutations respect the design.

Choices you make

options

Dissimilaritydefault euclidean

How unlike two rows are; the test asks its question of this dissimilarity, so choose it before looking.

  • Euclidean(default) — Straight-line distance; standardize first when variables have different units.
  • Manhattan (city block) — Sum of absolute differences; less dominated by one large difference than Euclidean.
  • Bray–Curtis — Σ|x − y| / Σ(x + y) for non-negative counts or abundances; ignores joint absences.
  • Jaccard (quantitative) — 2B/(1 + B) from Bray–Curtis B: a metric version for abundances.
  • Gower (range-scaled) — Mean absolute difference after scaling each variable to its range.
Transform firstdefault none

A transform of the variables applied before the dissimilarity.

  • None(default) — Use the values as they are.
  • Standardize (z-scores) — Each variable to mean 0 and SD 1, so units do not decide which variable dominates.
  • Scale to 0–1 — Each variable divided by its range after subtracting its minimum.
  • Hellinger — Square roots of each row's relative abundances; makes Euclidean distance suitable for species counts.
  • log(1 + x) — Damps very large counts before the dissimilarity.

hypothesis

Permutationsdefault 999

Label permutations; the smallest possible p is 1/(B + 1).

Significance leveldefault 0.05

Level used to read PERMANOVA together with PERMDISP.

posthoc

Pairwise comparisonsdefault on

With three or more groups, PERMANOVA for each pair of groups with Holm-adjusted p-values.

assumptions

PERMDISP centerdefault median

The center PERMDISP measures spread from.

  • Spatial median(default) — Distance to each group's spatial median (Anderson 2006; vegan's default) — robust to outliers.
  • Centroid — Distance to each group's centroid in principal-coordinate space.

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.

  • Similar spread across groups (PERMDISP)

    PERMANOVA tests location and spread together; when PERMDISP rejects, a significant result may be about spread.

  • Exchangeable rows

    Rows must be exchangeable under the null; give blocks, sites or subjects as strata.

  • Enough rows per group

    Very small groups give few distinct permutations.

What it reports

  • Tests: No group differences in the dissimilarities
f
PERMANOVA's F ratio; it has the form of ANOVA's F but its p-value comes from permutations, not the F table.
p
How surprising your data would be if the null hypothesis were true, as a probability.
r2
ANOVA on a dissimilarity matrix — a pseudo-F of between- to within-group squared distances, tested by shuffling labels.
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.
ss_between
Total squared distance from a mean. ANOVA splits it between sources to show where the variation comes from.
ss_within
Total squared distance from a mean. ANOVA splits it between sources to show where the variation comes from.
ss_total
Total squared distance from a mean. ANOVA splits it between sources to show where the variation comes from.
k
How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
n
How many independent units the analysis used; it sets precision and power.
n_perm
How many independent units the analysis used; it sets precision and power.
disp_f
The ratio of explained to unexplained variance, used by ANOVA and regression tests.
disp_p
Tests whether groups differ in spread — the mean distance of their rows to the group's spatial median or centroid.
verdict
The result in words, at the significance level stated with it. It says what the data are compatible with, not what is true.
missing_share
Values that were not recorded; how they went missing decides which fixes are safe.

Per group, level or term: dispersion[<group>], pair_p[<group> vs <group>]

Python and R

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

Default traps between the two languages

  • Both engines use the codesplash twins (codesplash.stats.mvdist ↔ codesplashr cs_mvd_*); label permutations come from the shared Wichmann–Hill stream, so permutation p-values match exactly.
  • PERMDISP's spatial median is found by Weiszfeld iterations to 1e-12; vegan::betadisper minimizes with optim (BFGS), so its F agrees with ours to about four significant digits.
Python

The exact script CodeSplash ran for example “Guide euclidean” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# PERMANOVA (permutational MANOVA)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method multivariate.permanova 1.0.1 · spec 8aef2caa41dfe3b9
# 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 itertools

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.stats import mvdist
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)

# %% Distances
# The dissimilarity between every pair of rows after the chosen transform (codesplash.stats.mvdist); all
# permutations come from the shared Wichmann–Hill stream, so Python and R draw the same relabellings.
variables = ["y1", "y2", "y3"]
transform_kind = "none"  # none | standardize | range | hellinger | log1p
metric = "euclidean"  # euclidean | manhattan | bray | jaccard | gower
seed = 42
n_perm = int(199)
DIST_LABEL = {"euclidean": "Euclidean", "manhattan": "Manhattan", "bray": "Bray–Curtis", "jaccard": "Jaccard", "gower": "Gower"}
TRANSFORM_LABEL = {"none": "", "standardize": "standardized ", "range": "range-scaled ", "hellinger": "Hellinger-transformed ", "log1p": "log(1 + x) "}
Y = df[variables].to_numpy(dtype=float)
n = int(Y.shape[0])
dims = len(variables)
if n > 5000:
    raise ValueError(f"Distance-based tests use an n × n matrix; {n} rows is too many (at most 5000). Filter or sample the data first.")
D = mvdist.distance(mvdist.transform(Y, transform_kind), metric)
dist_text = f"{DIST_LABEL[metric]} dissimilarity of the {TRANSFORM_LABEL[transform_kind]}variables"
g = "group"
levels = [str(lv) for lv in df[g].cat.categories]
codes = df[g].cat.codes.to_numpy().astype(int)
k = len(levels)
if k < 2:
    cs.cs_error("CS_E_TOO_FEW_GROUPS", column=g, min=2, k=k)
group_n = np.bincount(codes, minlength=k)
strata_col = None
strata = None

# %% Test
# PERMANOVA (Anderson 2001): pseudo-F = [(SS_T − SS_W)/(k − 1)] / [SS_W/(N − k)] from squared
# dissimilarities, p by permuting the group labels (within strata when given).
pairwise = True
dispersion_center = "median"  # median | centroid
alpha = 0.05
res = mvdist.permanova(D, codes, k, n_perm, seed, strata)
f, p = res["f"], res["p"]
# PERMDISP (Anderson 2006) is always run: PERMANOVA also reacts to unequal spread.
disp = mvdist.permdisp(D, codes, k, dispersion_center, False, n_perm, seed)

if p < alpha and disp["p"] >= alpha:
    verdict = "location"
    reading = "the groups differ in where they sit (their centers), and their spreads are similar, so PERMANOVA's result is about location."
elif p < alpha:
    verdict = "location_or_dispersion"
    reading = "the groups differ, but their spreads differ too (PERMDISP), so part or all of PERMANOVA's result may reflect dispersion rather than location — look at the PCoA plot and the dispersion table."
elif disp["p"] < alpha:
    verdict = "dispersion"
    reading = "no evidence that the centers differ, but the spreads do (PERMDISP): one group is more variable than another."
else:
    verdict = "none"
    reading = "no evidence that the groups differ in center or spread."

pair_rows = []
if pairwise and k > 2:
    combos = list(itertools.combinations(range(k), 2))
    raw = []
    for a, b in combos:
        sel = (codes == a) | (codes == b)
        sub = D[np.ix_(sel, sel)]
        sc = (codes[sel] == b).astype(int)
        st = None if strata is None else strata[sel]
        r = mvdist.permanova(sub, sc, 2, n_perm, seed, st)
        raw.append(r)
    padj = p_adjust([r["p"] for r in raw], "holm")
    for (a, b), r, pa in zip(combos, raw, padj):
        pair_rows.append({"a": levels[a], "b": levels[b], "f": r["f"], "r2": r["r2"], "p": r["p"], "p_adj": float(pa)})

# %% Assumptions
assumptions = [
    {"key": "dispersion", "label": "Similar spread across groups (PERMDISP)", "status": "pass" if disp["p"] >= alpha else "warn",
     "statistic": disp["f"], "p": disp["p"],
     "detail": f"PERMDISP F({disp['df1']}, {disp['df2']}) = {disp['f']:.3f}, permutation {cs.fmt_p(disp['p'])}"
               + ("." if disp["p"] >= alpha else "; spreads differ, so a significant PERMANOVA may reflect dispersion, not location (Anderson & Walsh 2013).")},
    {"key": "exchangeable", "label": "Exchangeable rows", "status": "info",
     "detail": ("Labels were permuted within " + strata_col + "." if strata_col else
                "Labels were permuted freely; for blocks, sites or repeated measures add them as strata so permutations respect the design.")},
]
if min(group_n) < 3:
    assumptions.append({"key": "group_size", "label": "Enough rows per group", "status": "warn",
                        "detail": f"The smallest group has {int(min(group_n))} rows; with so few the permutation distribution is coarse."})

# %% Result
summary = (f"PERMANOVA on the {dist_text} ({', '.join(variables)}) " +
           (f"found that the {k} groups of {g} differ (pseudo-F({res['df1']}, {res['df2']}) = {f:.3f}, R² = {res['r2']:.3f}, {cs.fmt_p(p)}, {n_perm} permutations); " if p < alpha
            else f"found no evidence that the {k} groups of {g} differ (pseudo-F({res['df1']}, {res['df2']}) = {f:.3f}, R² = {res['r2']:.3f}, {cs.fmt_p(p)}, {n_perm} permutations); ")
           + reading)
values = {"f": f, "p": p, "r2": res["r2"], "df1": res["df1"], "df2": res["df2"], "ss_between": res["ss_between"], "ss_within": res["ss_within"],
          "ss_total": res["ss_total"], "k": k, "n": n, "n_perm": n_perm, "disp_f": disp["f"], "disp_p": disp["p"], "verdict": verdict}
values["missing_share"] = n_dropped / n_input if n_input else 0.0
for lv, z in zip(levels, disp["group_mean"]):
    values[f"dispersion[{lv}]"] = float(z)
for r in pair_rows:
    values[f"pair_p[{r['a']} vs {r['b']}]"] = r["p_adj"]

tables = [
    {"key": "anova", "title": "PERMANOVA table",
     "columns": [{"key": "source", "label": "Source", "type": "string"}, {"key": "df", "label": "df", "type": "integer"},
                 {"key": "ss", "label": "Sum of squares", "type": "number"}, {"key": "r2", "label": "R²", "type": "number"},
                 {"key": "f", "label": "Pseudo-F", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}],
     "rows": [{"source": g, "df": res["df1"], "ss": res["ss_between"], "r2": res["r2"], "f": f, "p": p},
              {"source": "Residual", "df": res["df2"], "ss": res["ss_within"], "r2": 1 - res["r2"], "f": None, "p": None},
              {"source": "Total", "df": n - 1, "ss": res["ss_total"], "r2": 1.0, "f": None, "p": None}]},
    {"key": "dispersion", "title": f"Dispersion: distance to each group's {'spatial median' if dispersion_center == 'median' else 'centroid'} (PERMDISP)",
     "columns": [{"key": "group", "label": g, "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
                 {"key": "mean", "label": "Mean distance to center", "type": "number"}],
     "rows": [{"group": lv, "n": int(m), "mean": float(z)} for lv, m, z in zip(levels, group_n, disp["group_mean"])]},
    {"key": "decision", "title": "Reading PERMANOVA with PERMDISP",
     "columns": [{"key": "test", "label": "Test", "type": "string"}, {"key": "statistic", "label": "F", "type": "number"},
                 {"key": "p", "label": "p", "type": "pvalue"}, {"key": "meaning", "label": "What it says", "type": "string"}],
     "rows": [{"test": "PERMANOVA (location and spread)", "statistic": f, "p": p, "meaning": "Groups differ" if p < alpha else "No evidence of a difference"},
              {"test": "PERMDISP (spread only)", "statistic": disp["f"], "p": disp["p"], "meaning": "Spreads differ" if disp["p"] < alpha else "Spreads similar"},
              {"test": "Conclusion", "statistic": None, "p": None, "meaning": reading[0].upper() + reading[1:]}]},
]
if pair_rows:
    tables.append({"key": "pairwise", "title": "Pairwise PERMANOVA (Holm-adjusted)",
                   "columns": [{"key": "a", "label": "Group A", "type": "string"}, {"key": "b", "label": "Group B", "type": "string"},
                               {"key": "f", "label": "Pseudo-F", "type": "number"}, {"key": "r2", "label": "R²", "type": "number"},
                               {"key": "p", "label": "p", "type": "pvalue"}, {"key": "p_adj", "label": "Holm p", "type": "pvalue"}],
                   "rows": pair_rows})

pc = disp["pcoa"]
V = pc["vectors"]
pos = pc["positive"]
ax2 = V[:, 1] if V.shape[1] > 1 else np.zeros(n)
ex = pc["explained"]
lab1 = f"PCoA 1 ({100 * ex[0]:.1f}%)" if V.shape[1] else "PCoA 1"
lab2 = f"PCoA 2 ({100 * ex[1]:.1f}%)" if V.shape[1] > 1 else "PCoA 2"
cs.publish({
    "method": "multivariate.permanova",
    "methodVersion": "1.0.1",
    "title": "PERMANOVA",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "apa": f"PERMANOVA ({DIST_LABEL[metric]}), pseudo-F({res['df1']}, {res['df2']}) = {cs.fmt_num(f)}, R² = {res['r2']:.2f}, {cs.fmt_p(p)}",
    "statistics": [{"key": "f", "label": "Pseudo-F", "value": f}, {"key": "df1", "label": "df1", "value": res["df1"]},
                   {"key": "df2", "label": "df2", "value": res["df2"]}, {"key": "r2", "label": "R²", "value": res["r2"]},
                   {"key": "p", "label": "p", "value": p, "format": "p"}],
    "tables": tables,
    "effectSizes": [{"key": "r2", "label": "R²", "value": res["r2"], "method": "SS between / SS total of the dissimilarities"}],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"{dist_text}; p from {n_perm} label permutations on the shared seeded stream (seed {seed}), (1 + #F* ≥ F) / (B + 1)."
              + (f" Permutations were restricted within {strata_col}." if strata_col else ""),
              "PERMDISP is reported with PERMANOVA because PERMANOVA is sensitive to differences in spread as well as location."],
    "values": values,
    "charts": [cs.chart("ordination", "pcoa-centroids", f"Principal coordinates of the {DIST_LABEL[metric]} dissimilarities by {g}", {
        "x": cs.col(lab1, V[:, 0] if V.shape[1] else np.zeros(n)),
        "y": cs.col(lab2, ax2),
        "group": cs.col(g, df[g].astype(str).to_numpy(), levels=levels)}, controls={"center": dispersion_center, "spokes": True})],
})
R

The exact script CodeSplash ran for example “Guide euclidean” · R version 4.5.1 (2025-06-13)

# PERMANOVA (permutational MANOVA)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method multivariate.permanova 1.0.1 · spec 8aef2caa41dfe3b9
# 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)

# %% Distances
# The dissimilarity between every pair of rows after the chosen transform (codesplashr cs_mvd_*); all
# permutations come from the shared Wichmann-Hill stream, so Python and R draw the same relabellings.
variables <- c("y1", "y2", "y3")
transform_kind <- "none"  # none | standardize | range | hellinger | log1p
metric <- "euclidean"  # euclidean | manhattan | bray | jaccard | gower
seed <- 42
n_perm <- as.integer(199)
DIST_LABEL <- c(euclidean = "Euclidean", manhattan = "Manhattan", bray = "Bray–Curtis", jaccard = "Jaccard", gower = "Gower")
TRANSFORM_LABEL <- c(none = "", standardize = "standardized ", range = "range-scaled ", hellinger = "Hellinger-transformed ", log1p = "log(1 + x) ")
Y <- as.matrix(df[variables])
storage.mode(Y) <- "double"
n <- nrow(Y)
dims <- length(variables)
if (n > 5000) stop(sprintf("Distance-based tests use an n × n matrix; %d rows is too many (at most 5000). Filter or sample the data first.", n))
D <- cs_mvd_distance(cs_mvd_transform(Y, transform_kind), metric)
dist_text <- sprintf("%s dissimilarity of the %svariables", DIST_LABEL[[metric]], TRANSFORM_LABEL[[transform_kind]])
g <- "group"
levels_g <- levels(df[[g]])
codes <- as.integer(df[[g]]) - 1L
k <- length(levels_g)
if (k < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = g, min = 2, k = k)
group_n <- tabulate(codes + 1L, nbins = k)
strata_col <- NULL
strata <- NULL

# %% Test
# PERMANOVA (Anderson 2001): pseudo-F = [(SS_T - SS_W)/(k - 1)] / [SS_W/(N - k)] from squared
# dissimilarities, p by permuting the group labels (within strata when given).
pairwise <- TRUE
dispersion_center <- "median"  # median | centroid
alpha <- 0.05
res <- cs_mvd_permanova(D, codes, k, n_perm, seed, strata)
f <- res$f
p <- res$p
# PERMDISP (Anderson 2006) is always run: PERMANOVA also reacts to unequal spread.
disp <- cs_mvd_permdisp(D, codes, k, dispersion_center, FALSE, n_perm, seed)

if (p < alpha && disp$p >= alpha) {
  verdict <- "location"
  reading <- "the groups differ in where they sit (their centers), and their spreads are similar, so PERMANOVA's result is about location."
} else if (p < alpha) {
  verdict <- "location_or_dispersion"
  reading <- "the groups differ, but their spreads differ too (PERMDISP), so part or all of PERMANOVA's result may reflect dispersion rather than location — look at the PCoA plot and the dispersion table."
} else if (disp$p < alpha) {
  verdict <- "dispersion"
  reading <- "no evidence that the centers differ, but the spreads do (PERMDISP): one group is more variable than another."
} else {
  verdict <- "none"
  reading <- "no evidence that the groups differ in center or spread."
}

pair_rows <- NULL
if (pairwise && k > 2) {
  combos <- utils::combn(k, 2) - 1L
  raw <- lapply(seq_len(ncol(combos)), function(i) {
    a <- combos[1, i]
    b <- combos[2, i]
    sel <- codes == a | codes == b
    st <- if (is.null(strata)) NULL else strata[sel]
    cs_mvd_permanova(D[sel, sel, drop = FALSE], as.integer(codes[sel] == b), 2, n_perm, seed, st)
  })
  padj <- cs_p_adjust(vapply(raw, `[[`, 0, "p"), "holm")
  pair_rows <- data.frame(a = levels_g[combos[1, ] + 1L], b = levels_g[combos[2, ] + 1L],
                          f = vapply(raw, `[[`, 0, "f"), r2 = vapply(raw, `[[`, 0, "r2"),
                          p = vapply(raw, `[[`, 0, "p"), p_adj = padj)
}

# %% Assumptions
assumptions <- list(
  list(key = "dispersion", label = "Similar spread across groups (PERMDISP)", status = if (disp$p >= alpha) "pass" else "warn",
       statistic = disp$f, p = disp$p,
       detail = paste0(sprintf("PERMDISP F(%d, %d) = %.3f, permutation %s", disp$df1, disp$df2, disp$f, cs_fmt_p(disp$p)),
                       if (disp$p >= alpha) "." else "; spreads differ, so a significant PERMANOVA may reflect dispersion, not location (Anderson & Walsh 2013).")),
  list(key = "exchangeable", label = "Exchangeable rows", status = "info",
       detail = if (!is.null(strata_col)) paste0("Labels were permuted within ", strata_col, ".") else
         "Labels were permuted freely; for blocks, sites or repeated measures add them as strata so permutations respect the design.")
)
if (min(group_n) < 3) {
  assumptions[[length(assumptions) + 1]] <- list(key = "group_size", label = "Enough rows per group", status = "warn",
    detail = sprintf("The smallest group has %d rows; with so few the permutation distribution is coarse.", as.integer(min(group_n))))
}

# %% Result
summary <- paste0(sprintf("PERMANOVA on the %s (%s) ", dist_text, paste(variables, collapse = ", ")),
                  if (p < alpha) sprintf("found that the %d groups of %s differ (pseudo-F(%d, %d) = %.3f, R² = %.3f, %s, %d permutations); ",
                                         k, g, res$df1, res$df2, f, res$r2, cs_fmt_p(p), n_perm)
                  else sprintf("found no evidence that the %d groups of %s differ (pseudo-F(%d, %d) = %.3f, R² = %.3f, %s, %d permutations); ",
                               k, g, res$df1, res$df2, f, res$r2, cs_fmt_p(p), n_perm),
                  reading)
values <- list(f = f, p = p, r2 = res$r2, df1 = res$df1, df2 = res$df2, ss_between = res$ss_between, ss_within = res$ss_within,
               ss_total = res$ss_total, k = k, n = n, n_perm = n_perm, disp_f = disp$f, disp_p = disp$p, verdict = verdict)
values$missing_share <- if (n_input > 0) n_dropped / n_input else 0
for (i in seq_len(k)) values[[sprintf("dispersion[%s]", levels_g[i])]] <- disp$group_mean[i]
if (!is.null(pair_rows)) for (i in seq_len(nrow(pair_rows))) values[[sprintf("pair_p[%s vs %s]", pair_rows$a[i], pair_rows$b[i])]] <- pair_rows$p_adj[i]

tables <- list(
  list(key = "anova", title = "PERMANOVA table",
       columns = list(list(key = "source", label = "Source", type = "string"), list(key = "df", label = "df", type = "integer"),
                      list(key = "ss", label = "Sum of squares", type = "number"), list(key = "r2", label = "R²", type = "number"),
                      list(key = "f", label = "Pseudo-F", type = "number"), list(key = "p", label = "p", type = "pvalue")),
       rows = list(list(source = g, df = res$df1, ss = res$ss_between, r2 = res$r2, f = f, p = p),
                   list(source = "Residual", df = res$df2, ss = res$ss_within, r2 = 1 - res$r2, f = NULL, p = NULL),
                   list(source = "Total", df = n - 1, ss = res$ss_total, r2 = 1, f = NULL, p = NULL))),
  list(key = "dispersion", title = sprintf("Dispersion: distance to each group's %s (PERMDISP)", if (dispersion_center == "median") "spatial median" else "centroid"),
       columns = list(list(key = "group", label = g, type = "string"), list(key = "n", label = "n", type = "integer"),
                      list(key = "mean", label = "Mean distance to center", type = "number")),
       rows = data.frame(group = levels_g, n = as.integer(group_n), mean = disp$group_mean)),
  list(key = "decision", title = "Reading PERMANOVA with PERMDISP",
       columns = list(list(key = "test", label = "Test", type = "string"), list(key = "statistic", label = "F", type = "number"),
                      list(key = "p", label = "p", type = "pvalue"), list(key = "meaning", label = "What it says", type = "string")),
       rows = list(list(test = "PERMANOVA (location and spread)", statistic = f, p = p, meaning = if (p < alpha) "Groups differ" else "No evidence of a difference"),
                   list(test = "PERMDISP (spread only)", statistic = disp$f, p = disp$p, meaning = if (disp$p < alpha) "Spreads differ" else "Spreads similar"),
                   list(test = "Conclusion", statistic = NULL, p = NULL, meaning = paste0(toupper(substr(reading, 1, 1)), substring(reading, 2)))))
)
if (!is.null(pair_rows)) {
  tables[[length(tables) + 1]] <- list(key = "pairwise", title = "Pairwise PERMANOVA (Holm-adjusted)",
    columns = list(list(key = "a", label = "Group A", type = "string"), list(key = "b", label = "Group B", type = "string"),
                   list(key = "f", label = "Pseudo-F", type = "number"), list(key = "r2", label = "R²", type = "number"),
                   list(key = "p", label = "p", type = "pvalue"), list(key = "p_adj", label = "Holm p", type = "pvalue")),
    rows = pair_rows)
}

pc <- disp$pcoa
V <- pc$vectors
ex <- pc$explained
ax1 <- if (ncol(V) > 0) V[, 1] else rep(0, n)
ax2 <- if (ncol(V) > 1) V[, 2] else rep(0, n)
lab1 <- if (ncol(V) > 0) sprintf("PCoA 1 (%.1f%%)", 100 * ex[1]) else "PCoA 1"
lab2 <- if (ncol(V) > 1) sprintf("PCoA 2 (%.1f%%)", 100 * ex[2]) else "PCoA 2"
cs_publish(list(
  method = "multivariate.permanova",
  methodVersion = "1.0.1",
  title = "PERMANOVA",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = summary,
  apa = sprintf("PERMANOVA (%s), pseudo-F(%d, %d) = %s, R² = %.2f, %s", DIST_LABEL[[metric]], res$df1, res$df2, cs_fmt_num(f), res$r2, cs_fmt_p(p)),
  statistics = list(list(key = "f", label = "Pseudo-F", value = f), list(key = "df1", label = "df1", value = res$df1),
                    list(key = "df2", label = "df2", value = res$df2), list(key = "r2", label = "R²", value = res$r2),
                    list(key = "p", label = "p", value = p, format = "p")),
  tables = tables,
  effectSizes = list(list(key = "r2", label = "R²", value = res$r2, method = "SS between / SS total of the dissimilarities")),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(paste0(sprintf("%s; p from %d label permutations on the shared seeded stream (seed %d), (1 + #F* ≥ F) / (B + 1).", dist_text, n_perm, as.integer(seed)),
                      if (!is.null(strata_col)) sprintf(" Permutations were restricted within %s.", strata_col) else ""),
               "PERMDISP is reported with PERMANOVA because PERMANOVA is sensitive to differences in spread as well as location."),
  values = values,
  charts = list(cs_chart("ordination", "pcoa-centroids", sprintf("Principal coordinates of the %s dissimilarities by %s", DIST_LABEL[[metric]], g), list(
    x = cs_col(lab1, ax1),
    y = cs_col(lab2, ax2),
    group = cs_col(g, as.character(df[[g]]), levels = levels_g)), controls = list(center = dispersion_center, spokes = TRUE)))
))

Sources

  • Anderson, M. J. (2001). A new method for non-parametric multivariate analysis of variance. Austral Ecology, 26, 32–46.
  • McArdle, B. H., & Anderson, M. J. (2001). Fitting multivariate models to community data: a comment on distance-based redundancy analysis. Ecology, 82, 290–297.
  • Anderson, M. J. (2006). Distance-based tests for homogeneity of multivariate dispersions. Biometrics, 62, 245–253.
  • Anderson, M. J., & Walsh, D. C. I. (2013). PERMANOVA, ANOSIM, and the Mantel test in the face of heterogeneous dispersions. Ecological Monographs, 83, 557–574.

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