PERMANOVA: group tests from any distance
Run an ANOVA on a matrix of dissimilarities, pick a dissimilarity that suits your data, and read the result beside PERMDISP.
What runs in CodeSplash
- STAT170PERMANOVA Runs in CodeSplash
- PERMANOVA (permutational MANOVA) Verified in Python and R
You will be able to
- Explain how PERMANOVA turns pairwise dissimilarities into a pseudo-F
- Choose a dissimilarity and transformation that suit the data
- Read pseudo-F, R² and the PERMDISP check together
When a covariance matrix won't work
ReadTwenty meadow plots are scored for thirty plant species. MANOVA needs more rows than outcomes, and these counts are skewed and mostly zero.
PERMANOVAPERMANOVAANOVA on a dissimilarity matrix — a pseudo-F of between- to within-group squared distances, tested by shuffling labels. needs none of that. You first choose how to measure the dissimilarityDissimilarityA number for how unlike two rows are; distance-based tests ask their question of this matrix of all pairs. between two rows, then work from the matrix of pairwise dissimilarities.
Sums of squares from distances
ReadAnderson (2001) showed that sums of squares can be written using pairwise distances alone:
Then , and the pseudo-FPseudo-FPERMANOVA's F ratio; it has the form of ANOVA's F but its p-value comes from permutations, not the F table. is built as in ANOVA:
There is no F table to look up. Group labels are shuffled to give the reference distribution.
Pick a dissimilarity
PredictPredict first
Two meadow plots both lack a rare orchid. Should this shared zero make them count as similar?
Which dissimilarity respects your answer?
Reveal
Bray–Curtis. Sharing an absence says little about two plots, as a species can be missing for many reasons. Euclidean treats shared zeros as similarity, which is misleading for sparse counts.
| Dissimilarity | Good for |
|---|---|
| Euclidean | Continuous measures on a common or standardized scale |
| Manhattan | Same, with less weight on large single gaps |
| Bray–CurtisBray–Curtis dissimilarityΣ|x − y| / Σ(x + y) — the share of two rows' total abundance that is not shared; 0 identical, 1 nothing in common. | Abundance counts |
| Jaccard (quantitative) | Mostly about which species are shared |
| Gower (range-scaled) | Variables on different scales |
Read a result
In the appPERMANOVA (Bray–Curtis), pseudo-F(3, 16) = 2.77, R² = 0.34, p = .010
- Pseudo-F
- 2.767
- df1
- 3
- df2
- 16
- R²
- 0.3416
- p
- .010
Effect size
- R² 0.3416
Plots
View data
| Management | PCoA 1 (37.4%) | PCoA 2 (22.3%) |
|---|---|---|
| SF | −0.3547 | −0.2567 |
| BF | −0.2946 | −0.1861 |
| SF | −0.0728 | −0.2909 |
| SF | −0.0693 | −0.2642 |
| HF | −0.3071 | 0.0303 |
| HF | −0.2530 | 0.0942 |
| HF | −0.3096 | −0.0191 |
| HF | 0.1773 | −0.1701 |
| HF | 0.0174 | −0.2467 |
| BF | −0.3112 | 0.0546 |
| BF | −0.2023 | 0.1411 |
| SF | 0.1955 | −0.1259 |
| SF | 0.1799 | −0.2152 |
| NM | 0.4301 | 0.0861 |
| NM | 0.4877 | 0.1150 |
| SF | 0.5112 | −0.1109 |
| NM | −0.1948 | 0.4965 |
| NM | −0.1334 | 0.2411 |
| NM | −0.0054 | 0.4691 |
| NM | 0.5092 | 0.1575 |
Assumptions
- Similar spread across groups (PERMDISP) — PERMDISP F(3, 16) = 1.951, permutation p = .195.
- Exchangeable rows — Labels were permuted freely; for blocks, sites or repeated measures add them as strata so permutations respect the design.
PERMANOVA table
| Source | df | Sum of squares | R² | Pseudo-F | p |
|---|---|---|---|---|---|
| Management | 3 | 1.469 | 0.3416 | 2.767 | .010 |
| Residual | 16 | 2.830 | 0.6584 | — | — |
| Total | 19 | 4.299 | 1 | — | — |
Dispersion: distance to each group's spatial median (PERMDISP)
| Management | n | Mean distance to center |
|---|---|---|
| BF | 3 | 0.2196 |
| HF | 5 | 0.2791 |
| NM | 6 | 0.4510 |
| SF | 6 | 0.3640 |
Reading PERMANOVA with PERMDISP
| Test | F | p | What it says |
|---|---|---|---|
| PERMANOVA (location and spread) | 2.767 | .010 | Groups differ |
| PERMDISP (spread only) | 1.951 | .195 | Spreads similar |
| Conclusion | — | — | The groups differ in where they sit (their centers), and their spreads are similar, so PERMANOVA's result is about location. |
Pairwise PERMANOVA (Holm-adjusted)
| Group A | Group B | Pseudo-F | R² | p | Holm p |
|---|---|---|---|---|---|
| BF | HF | 1.568 | 0.2071 | .155 | .220 |
| BF | NM | 2.715 | 0.2795 | .025 | .150 |
| BF | SF | 2.515 | 0.2643 | .070 | .210 |
| HF | NM | 3.423 | 0.2755 | .050 | .200 |
| HF | SF | 1.857 | 0.1711 | .110 | .220 |
| NM | SF | 3.426 | 0.2552 | .025 | .150 |
- Bray–Curtis 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.
The exact R script · R 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 1475febcfbe6b5ed
# Dataset: mv_dune (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_dune.parquet", col_select = c("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", "Management")))
n_input <- nrow(df)
df[["Management"]] <- factor(df[["Management"]], levels = c("BF", "HF", "NM", "SF")) # stored level order
df <- df[stats::complete.cases(df[c("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", "Management")]), , 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("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", "Management")) # 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("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")
transform_kind <- "none" # none | standardize | range | hellinger | log1p
metric <- "bray" # 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 <- "Management"
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)))
))
PERMANOVA (Bray–Curtis), pseudo-F(3, 16) = 2.77, R² = 0.34, p = .010
- Pseudo-F
- 2.767
- df1
- 3
- df2
- 16
- R²
- 0.3416
- p
- .010
Effect size
- R² 0.3416
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Similar spread across groups (PERMDISP) — PERMDISP F(3, 16) = 1.951, permutation p = .195.
- Exchangeable rows — Labels were permuted freely; for blocks, sites or repeated measures add them as strata so permutations respect the design.
PERMANOVA table
| Source | df | Sum of squares | R² | Pseudo-F | p |
|---|---|---|---|---|---|
| Management | 3 | 1.469 | 0.3416 | 2.767 | .010 |
| Residual | 16 | 2.830 | 0.6584 | — | — |
| Total | 19 | 4.299 | 1 | — | — |
Dispersion: distance to each group's spatial median (PERMDISP)
| Management | n | Mean distance to center |
|---|---|---|
| BF | 3 | 0.2196 |
| HF | 5 | 0.2791 |
| NM | 6 | 0.4510 |
| SF | 6 | 0.3640 |
Reading PERMANOVA with PERMDISP
| Test | F | p | What it says |
|---|---|---|---|
| PERMANOVA (location and spread) | 2.767 | .010 | Groups differ |
| PERMDISP (spread only) | 1.951 | .195 | Spreads similar |
| Conclusion | — | — | The groups differ in where they sit (their centers), and their spreads are similar, so PERMANOVA's result is about location. |
Pairwise PERMANOVA (Holm-adjusted)
| Group A | Group B | Pseudo-F | R² | p | Holm p |
|---|---|---|---|---|---|
| BF | HF | 1.568 | 0.2071 | .155 | .220 |
| BF | NM | 2.715 | 0.2795 | .025 | .150 |
| BF | SF | 2.515 | 0.2643 | .070 | .210 |
| HF | NM | 3.423 | 0.2755 | .050 | .200 |
| HF | SF | 1.857 | 0.1711 | .110 | .220 |
| NM | SF | 3.426 | 0.2552 | .025 | .150 |
- Bray–Curtis 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.
The exact Python script · Python 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 1475febcfbe6b5ed
# Dataset: mv_dune (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_dune.parquet", columns=["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", "Management"])
n_input = len(df)
df["Management"] = pd.Categorical(df["Management"], categories=["BF", "HF", "NM", "SF"]) # stored level order
df = df.dropna(subset=["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", "Management"]) # listwise deletion over the analysis columns
df["Management"] = df["Management"].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, ["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", "Management"]) # 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 = ["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"]
transform_kind = "none" # none | standardize | range | hellinger | log1p
metric = "bray" # 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 = "Management"
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})],
})
Pseudo-F(3, 16) = 2.77, = 0.34, and p = 0.010 with 199 permutations.
Management type accounts for about a third of the dissimilarity. Check the Pairwise PERMANOVA (Holm-adjusted) table. With three to six plots per group, would you expect any single pair to reach 0.05?
Location, or spread?
PredictPredict first
PERMANOVA is often described as a test of group centers. If two groups share a center but one is more spread out, can PERMANOVA still reject?
Reveal
It can, especially with unbalanced groups. That is why the card runs PERMDISP too. Here PERMDISP gives 0.20, so the verdict is "location". On iris with Gower, PERMDISP gives 0.01 and the card says location or dispersion: pseudo-F = 375.1 may reflect either.
Strata and transformations
ReflectStrata limits permutations to within blocks, which is right when rows from one site or batch aren't exchangeable with rows from another.
Transform first changes what the dissimilarity sees. Hellinger and log(1 + x) reduce the pull of a few dominant species. On the meadow plots with a Hellinger transform, strata, and a different grouping, pseudo-F = 1.01, p = 0.19.
What are the blocks in your own data? Which groupings have rows that can't be swapped freely?
Check your understanding
CheckpointCheck yourself
In a PERMANOVA table, = 1.4686 and = 4.299. What is ? Give two decimals.
Show the answer
Answer: 0.341610672392544
. This is the share of total dissimilarity between groups.
Check yourself
With = 1.4686 on 3 df and = 2.8304 on 16 df, what is the pseudo-F? Give two decimals.
Show the answer
Answer: 2.76724349818111
.
Check yourself
PERMANOVA gives p = 0.002 and PERMDISP gives p = 0.001. Which conclusion is sound?
Show the answer
Answer: c
With both significant, you can't attribute the result to location. The ordination plot helps, and balanced groups make PERMANOVA less sensitive to spread.
Do it in CodeSplash
In the appChoose Variables and Groups, then Dissimilarity and Transform first. The PCoA chart shows group centers. Read Reading PERMANOVA with PERMDISP on the card.
import pandas as pd
from scipy.spatial.distance import pdist, squareform
from skbio.stats.distance import DistanceMatrix, permanova
df = pd.read_csv("dune.csv")
species = df.drop(columns=["Management"])
D = DistanceMatrix(squareform(pdist(species.to_numpy(), "braycurtis")))
print(permanova(D, df["Management"].to_numpy(), permutations=999))# install.packages("vegan")
library(vegan)
data(dune); data(dune.env)
adonis2(dune ~ Management, data = dune.env, method = "bray", permutations = 999)Recap
Recap- PERMANOVA is an ANOVA built from pairwise dissimilarities, calibrated by shuffling labels.
- The dissimilarity is your main modeling decision. Choose it for what "similar" means in your data.
- Pseudo-F can respond to spread as well as center, so read it beside PERMDISP.
- Use strata when rows aren't freely exchangeable.
Concepts in this lesson