Skip to content

BMultivariate · multivariate.mrpp

MRPP (multi-response permutation procedure)

Are rows within each group more alike than rows picked at random?

MRPP averages the dissimilarities within each group (δ) and asks whether δ is smaller than expected when group labels are shuffled; A = 1 − δ/E(δ) is the chance-corrected within-group agreement. Small δ is the evidence, so the p-value is the lower tail.

Verified in Python and R Python and R agree to 10 decimals Seeded Also called MRPP, multi-response permutation procedure, multiresponse permutation procedure…

A real result

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

MRPP: multi-response permutation procedureRecorded · Python and R agreeRecorded 2026-11-17 · 10 values compared
R

MRPP (Euclidean), δ = 2.18, A = 0.037, p = .005

δ
2.177
E(δ)
2.260
A
0.0370
p
.005

Effect size

  • Chance-corrected within-group agreement A 0.0370

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 — MRPP compares within-group distances, so a tight group can drive a significant result on its own; see the class δ table.
  • Exchangeable rows — Labels were permuted freely; give blocks or sites as strata so permutations respect the design.

Mean within-group dissimilarity

groupnδ (mean dissimilarity)
g1402.320
g2502.062
  • Euclidean dissimilarity of the variables; group weights n_g / N; lower-tail p from 199 label permutations (seed 42).
Python

MRPP (Euclidean), δ = 2.18, A = 0.037, p = .005

δ
2.177
E(δ)
2.260
A
0.0370
p
.005

Effect size

  • Chance-corrected within-group agreement A 0.0370

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

Assumptions

  • Similar spread across groups — MRPP compares within-group distances, so a tight group can drive a significant result on its own; see the class δ table.
  • Exchangeable rows — Labels were permuted freely; give blocks or sites as strata so permutations respect the design.

Mean within-group dissimilarity

groupnδ (mean dissimilarity)
g1402.320
g2502.062
  • Euclidean dissimilarity of the variables; group weights n_g / N; lower-tail p from 199 label permutations (seed 42).

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 pairsmv_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
  • Mite strata df weightsmv_mite · group: Shrub · strata: Topo · variables: Brachy, PHTH, HPAV, RARD, SSTR, Protopl, MEGR, MPRO, TVIE, HMIN
  • 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

What you need

Variablesnumeric · 1–200 columns
The numeric variables (or species counts) whose dissimilarities are averaged.
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.

Choices you make

options

Dissimilaritydefault euclidean

How unlike two rows are.

  • Euclidean(default) — Straight-line distance (not squared — MRPP uses distances on their own scale).
  • Manhattan (city block) — Sum of absolute differences.
  • Bray–Curtis — For non-negative counts or abundances.
  • Jaccard (quantitative) — 2B/(1 + B) from Bray–Curtis B.
  • 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.
  • Scale to 0–1 — Each variable to its range.
  • Hellinger — Square roots of each row's relative abundances.
  • log(1 + x) — Damps very large counts.

hypothesis

Group weightsdefault n

How the groups' mean within-group dissimilarities are combined into δ; choose before testing.

  • n_g / N(default) — Weights proportional to group size (Mielke's recommended C₁; vegan weight.type = 1).
  • (n_g − 1) / (N − k) — Degrees-of-freedom weights (vegan weight.type = 2).
  • Pairs within groups — Weights proportional to the number of within-group pairs (vegan weight.type = 3).
Permutationsdefault 999

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

Significance leveldefault 0.05

Level used in the narrative.

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

    A single tight group can make δ small on its own.

  • Exchangeable rows

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

What it reports

  • Tests: No within-group agreement beyond chance
delta
Asks whether rows within groups are closer than random sets of the same sizes; A = 1 − δ/E(δ).
expected_delta
Asks whether rows within groups are closer than random sets of the same sizes; A = 1 − δ/E(δ).
a
Asks whether rows within groups are closer than random sets of the same sizes; A = 1 − δ/E(δ).
p
How surprising your data would be if the null hypothesis were true, as a probability.
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.
missing_share
Values that were not recorded; how they went missing decides which fixes are safe.

Per group, level or term: class_delta[<group>]

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

  • Both engines use the codesplash twins with the shared Wichmann–Hill permutations, so δ, A and p are identical; vegan::mrpp gives the same δ, E(δ) and A.
Python

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

# MRPP (multi-response permutation procedure)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method multivariate.mrpp 1.0.1 · spec e6313eab7539448d
# 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

import codesplash as cs
from codesplash.stats import mvdist

# %% 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
# MRPP (Mielke, Berry & Johnson 1976): δ = weighted mean of the within-group mean dissimilarities,
# A = 1 − δ / E(δ) with E(δ) the mean of all dissimilarities; small δ is evidence, so p is the lower tail.
weighting = "n"  # n | n_minus_1 | pairs
alpha = 0.05
res = mvdist.mrpp(D, codes, k, weighting, n_perm, seed, strata)
delta, p, a = res["delta"], res["p"], res["a"]

# %% Assumptions
assumptions = [
    {"key": "dispersion", "label": "Similar spread across groups", "status": "info",
     "detail": "MRPP compares within-group distances, so a tight group can drive a significant result on its own; see the class δ table."},
    {"key": "exchangeable", "label": "Exchangeable rows", "status": "info",
     "detail": ("Labels were permuted within " + strata_col + "." if strata_col else
                "Labels were permuted freely; give blocks or sites as strata so permutations respect the design.")},
]

# %% Result
summary = (f"MRPP on the {dist_text}: the rows of each group of {g} are " +
           ("more alike than expected by chance" if p < alpha else "not more alike than expected by chance")
           + f" (δ = {delta:.4g} vs E(δ) = {res['expected_delta']:.4g}, A = {a:.3f}, {cs.fmt_p(p)}, {n_perm} permutations).")
values = {"delta": delta, "expected_delta": res["expected_delta"], "a": a, "p": p, "k": k, "n": n, "n_perm": n_perm}
for lv, cd in zip(levels, res["class_delta"]):
    values[f"class_delta[{lv}]"] = float(cd)
values["missing_share"] = n_dropped / n_input if n_input else 0.0
WEIGHT_TEXT = {"n": "n_g / N", "n_minus_1": "(n_g − 1) / (N − k)", "pairs": "n_g(n_g − 1) / Σ n_g(n_g − 1)"}
pc = mvdist.pcoa(D)
V, ex = pc["vectors"], pc["explained"]
ax1 = V[:, 0] if V.shape[1] else np.zeros(n)
ax2 = V[:, 1] if V.shape[1] > 1 else np.zeros(n)
cs.publish({
    "method": "multivariate.mrpp",
    "methodVersion": "1.0.1",
    "title": "MRPP: multi-response permutation procedure",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "apa": f"MRPP ({DIST_LABEL[metric]}), δ = {cs.fmt_num(delta)}, A = {a:.3f}, {cs.fmt_p(p)}",
    "statistics": [{"key": "delta", "label": "δ", "value": delta}, {"key": "expected_delta", "label": "E(δ)", "value": res["expected_delta"]},
                   {"key": "a", "label": "A", "value": a}, {"key": "p", "label": "p", "value": p, "format": "p"}],
    "tables": [{"key": "classes", "title": "Mean within-group dissimilarity",
                "columns": [{"key": "group", "label": g, "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
                            {"key": "delta", "label": "δ (mean dissimilarity)", "type": "number"}],
                "rows": [{"group": lv, "n": int(m), "delta": float(cd)} for lv, m, cd in zip(levels, group_n, res["class_delta"])]}],
    "effectSizes": [{"key": "a", "label": "Chance-corrected within-group agreement A", "value": a,
                     "method": "1 − δ / E(δ); 0 = no more alike than chance, 1 = identical within groups"}],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"{dist_text}; group weights {WEIGHT_TEXT[weighting]}; lower-tail p from {n_perm} label permutations (seed {seed})."
              + (f" Permutations were restricted within {strata_col}." if strata_col else "")],
    "values": values,
    "charts": [cs.chart("ordination", "pcoa-centroids", f"Principal coordinates of the {DIST_LABEL[metric]} dissimilarities by {g}", {
        "x": cs.col(f"PCoA 1 ({100 * ex[0]:.1f}%)" if V.shape[1] else "PCoA 1", ax1),
        "y": cs.col(f"PCoA 2 ({100 * ex[1]:.1f}%)" if V.shape[1] > 1 else "PCoA 2", ax2),
        "group": cs.col(g, df[g].astype(str).to_numpy(), levels=levels)}, controls={"center": "centroid", "spokes": False, "hulls": True})],
})
R

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

# MRPP (multi-response permutation procedure)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method multivariate.mrpp 1.0.1 · spec e6313eab7539448d
# 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
# MRPP (Mielke, Berry & Johnson 1976): delta = weighted mean of the within-group mean dissimilarities,
# A = 1 - delta / E(delta) with E(delta) the mean of all dissimilarities; small delta is evidence (lower tail).
weighting <- "n"  # n | n_minus_1 | pairs
alpha <- 0.05
res <- cs_mvd_mrpp(D, codes, k, weighting, n_perm, seed, strata)
delta <- res$delta
p <- res$p
a <- res$a

# %% Assumptions
assumptions <- list(
  list(key = "dispersion", label = "Similar spread across groups", status = "info",
       detail = "MRPP compares within-group distances, so a tight group can drive a significant result on its own; see the class δ table."),
  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; give blocks or sites as strata so permutations respect the design.")
)

# %% Result
summary <- paste0(sprintf("MRPP on the %s: the rows of each group of %s are ", dist_text, g),
                  if (p < alpha) "more alike than expected by chance" else "not more alike than expected by chance",
                  sprintf(" (δ = %s vs E(δ) = %s, A = %.3f, %s, %d permutations).", format(signif(delta, 4)), format(signif(res$expected_delta, 4)), a, cs_fmt_p(p), n_perm))
values <- list(delta = delta, expected_delta = res$expected_delta, a = a, p = p, k = k, n = n, n_perm = n_perm)
for (i in seq_len(k)) values[[sprintf("class_delta[%s]", levels_g[i])]] <- res$class_delta[i]
values$missing_share <- if (n_input > 0) n_dropped / n_input else 0
WEIGHT_TEXT <- c(n = "n_g / N", n_minus_1 = "(n_g − 1) / (N − k)", pairs = "n_g(n_g − 1) / Σ n_g(n_g − 1)")
pc <- cs_mvd_pcoa(D)
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)
cs_publish(list(
  method = "multivariate.mrpp",
  methodVersion = "1.0.1",
  title = "MRPP: multi-response permutation procedure",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = summary,
  apa = sprintf("MRPP (%s), δ = %s, A = %.3f, %s", DIST_LABEL[[metric]], cs_fmt_num(delta), a, cs_fmt_p(p)),
  statistics = list(list(key = "delta", label = "δ", value = delta), list(key = "expected_delta", label = "E(δ)", value = res$expected_delta),
                    list(key = "a", label = "A", value = a), list(key = "p", label = "p", value = p, format = "p")),
  tables = list(list(key = "classes", title = "Mean within-group dissimilarity",
    columns = list(list(key = "group", label = g, type = "string"), list(key = "n", label = "n", type = "integer"),
                   list(key = "delta", label = "δ (mean dissimilarity)", type = "number")),
    rows = data.frame(group = levels_g, n = as.integer(group_n), delta = res$class_delta))),
  effectSizes = list(list(key = "a", label = "Chance-corrected within-group agreement A", value = a,
                          method = "1 − δ / E(δ); 0 = no more alike than chance, 1 = identical within groups")),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(paste0(sprintf("%s; group weights %s; lower-tail p from %d label permutations (seed %d).", dist_text, WEIGHT_TEXT[[weighting]], n_perm, as.integer(seed)),
                      if (!is.null(strata_col)) sprintf(" Permutations were restricted within %s.", strata_col) else "")),
  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(if (ncol(V) > 0) sprintf("PCoA 1 (%.1f%%)", 100 * ex[1]) else "PCoA 1", ax1),
    y = cs_col(if (ncol(V) > 1) sprintf("PCoA 2 (%.1f%%)", 100 * ex[2]) else "PCoA 2", ax2),
    group = cs_col(g, as.character(df[[g]]), levels = levels_g)), controls = list(center = "centroid", spokes = FALSE, hulls = TRUE)))
))

Sources

  • Mielke, P. W., Berry, K. J., & Johnson, E. S. (1976). Multi-response permutation procedures for a priori classifications. Communications in Statistics — Theory and Methods, 5, 1409–1424.
  • McCune, B., & Grace, J. B. (2002). Analysis of Ecological Communities, ch. 24. MjM Software Design.

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