Skip to content

BMultivariate · multivariate.mantel

Mantel test (and partial Mantel, correlogram)

Are two sets of dissimilarities between the same rows related — for example, community and environment, or genes and geography?

The Mantel test correlates the pairwise dissimilarities of two sets of variables measured on the same rows and tests the correlation by permuting whole rows of one matrix. Add a third set for the partial Mantel test, or ask for a correlogram to see how similarity changes across distance classes of the second set (e.g. geographic coordinates).

Verified in Python and R Python and R agree to 10 decimals Seeded Also called Mantel test, partial Mantel test, Mantel correlogram…

A real result

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

Mantel testRecorded · Python and R agreeRecorded 2026-11-17 · 11 values compared
R

Mantel test, r_M = -0.06, p = .725

r_M
−0.0624
p
.725
Pairs
190

Effect size

  • Mantel r −0.0624

Plots

Dissimilarity pairsDo pairs of rows that differ more in one set of variables also differ more in another (the Mantel test's question)?
View data
Euclidean dissimilarity of y1, y2, y3Euclidean dissimilarity of x1, x2, x3
3.1812.517
1.4451.131
2.3672.394
1.9491.287
2.1134.567
3.4343.052
1.3791.759
3.4452.223
4.2402.778
2.8820.9502
3.5691.648
2.2640.7794
2.3521.891
2.1223.152
1.8711.942
2.7230.9305
1.0640.6689
1.0942.060
2.8990.5476
2.7032.631
3.1611.967
2.8781.677
1.3202.602
2.7071.928
3.1661.203
1.3921.442
1.0642.016
3.6202.092
0.71891.096
2.3131.914
1.5371.041
3.3522.073
2.1282.945
3.1572.740
2.6532.288
3.8331.020
1.4182.593
0.97513.240
2.2511.691
2.1564.982
2.3793.767
2.2142.022
2.6402.858
3.6803.571
1.6461.023
2.8082.045
1.6931.224
2.3592.417
1.0463.163
1.1862.990
2.3322.042
1.7850.5617
2.5222.561
2.0000.8166
2.9631.910
2.9312.710
2.2070.8108
3.0731.833
2.8240.9774
3.9960.4829

First 60 of 190 rows.

Assumptions

  • Linear relation between the dissimilarities — The Mantel r measures a linear (Pearson) or monotone (Spearman) relation between pairwise dissimilarities, not between the raw variables.
  • Exchangeable objects — Rows are permuted as whole objects; with spatial or temporal structure in both matrices the permutation p is too small (Legendre, Fortin & Borcard 2015).

Upper quantiles of the permutation distribution

Quantiler_M
90%0.1234
95%0.1469
97.5%0.1737
99%0.1935
  • Mantel r over 190 pairs of rows; greater p from 199 row permutations of the first matrix (seed 42).
Python

Mantel test, r_M = -0.06, p = .725

r_M
−0.0624
p
.725
Pairs
190

Effect size

  • Mantel r −0.0624

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

Assumptions

  • Linear relation between the dissimilarities — The Mantel r measures a linear (Pearson) or monotone (Spearman) relation between pairwise dissimilarities, not between the raw variables.
  • Exchangeable objects — Rows are permuted as whole objects; with spatial or temporal structure in both matrices the permutation p is too small (Legendre, Fortin & Borcard 2015).

Upper quantiles of the permutation distribution

Quantiler_M
90%0.1234
95%0.1469
97.5%0.1737
99%0.1935
  • Mantel r over 190 pairs of rows; greater p from 199 row permutations of the first matrix (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_mantel_guide · x_variables: x1, x2, x3 · y_variables: y1, y2, y3
  • Vare bray chemmv_vare · x_variables: Callvulg, Empenigr, Rhodtome, Vaccmyrt, Vaccviti, Pinusylv, Descflex, Betupube, Vacculig, Diphcomp, Dicrsp, Dicrfusc, Dicrpoly, Hylosple, Pleuschr, Polypili, Polyjuni, Polycomm, Pohlnuta, Ptilcili, Barbhatc, Cladarbu, Cladrang, Cladstel, Cladunci, Cladcocc, Cladcorn, Cladgrac, Cladfimb, Cladcris, Cladchlo, Cladbotr, Cladamau, Cladsp, Cetreric, Cetrisla, Flavniva, Nepharct, Stersp, Peltapht, Icmaeric, Cladcerv, Claddefo, Cladphyl · y_variables: N, P, K, Ca, Mg, S, Al, Fe, Mn, Zn, Mo, Baresoil, Humdepth, pH
  • Vare partial spearmanmv_vare · x_variables: Callvulg, Empenigr, Vaccmyrt, Vaccviti, Pleuschr, Cladarbu, Cladrang, Cladstel · y_variables: N, P, K, Ca, Mg · z_variables: Al, Fe, pH
  • Mite correlogrammv_mite · x_variables: Brachy, PHTH, HPAV, RARD, SSTR, Protopl, MEGR, MPRO, TVIE, HMIN, HMIN2, NPRA, TVEL, ONOV, SUCT, LCIL · y_variables: x, y
  • Degenerate n3mv_mantel_guide · x_variables: x1, x2, x3 · y_variables: y1, y2, y3

In the guides

Tests from the statistics guide this method runs

Where it sits in the decision guides

  • Continuous–continuous: Pearson / Spearman / Kendall · Statistics Guide · C — Test association

What you need

First setnumeric · 1–200 columns
Variables whose dissimilarities form the first matrix (its rows are permuted), e.g. species counts.
Second setnumeric · 1–200 columns
Variables for the second matrix, e.g. environment or x/y coordinates (the correlogram's distance classes).
Control set (optional)numeric · 0–50 columns
For the partial Mantel test, variables whose standardized Euclidean distances are held constant.

Choices you make

options

First-set dissimilaritydefault bray

Dissimilarity for the first set.

  • Euclidean — Straight-line distance.
  • Manhattan (city block) — Sum of absolute differences.
  • Bray–Curtis(default) — 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.
First-set transformdefault none

Transform of the first set before its 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.
Second-set dissimilaritydefault euclidean

Dissimilarity for the second set.

  • Euclidean(default) — Straight-line distance; use it for coordinates.
  • 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.
Second-set transformdefault standardize

Transform of the second set before its dissimilarity.

  • None — Use the values as they are — keep coordinates unscaled.
  • Standardize (z-scores)(default) — Each variable to mean 0 and SD 1 (environmental variables in different units).
  • Scale to 0–1 — Each variable to its range.
  • Hellinger — Square roots of each row's relative abundances.
  • log(1 + x) — Damps very large values.

hypothesis

Correlationdefault pearson

The correlation between the two dissimilarity vectors.

  • Pearson(default) — Linear correlation of the dissimilarities (Mantel 1967).
  • Spearman — Rank correlation: any monotone relation between the dissimilarities.
Alternativedefault greater

The relation you expect, stated before testing.

  • Positive relation(default) — Rows far apart in one set are far apart in the other (the usual one-sided Mantel test).
  • Either direction — Two-sided p.
  • Negative relation — One-sided in the other direction.
Permutationsdefault 999

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

Significance leveldefault 0.05

Level used in the narrative and the correlogram.

statistics

Mantel correlogramdefault off

Mantel tests within distance classes of the second set, with a progressive Bonferroni correction.

Distance classesdefault 0

Number of equal-width classes; 0 uses Sturges' rule on the number of pairs.

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.

  • Linear relation between the dissimilarities

    Mantel r is about pairwise dissimilarities, not the raw variables; use Spearman for monotone relations.

  • Exchangeable objects

    Spatial or temporal autocorrelation in both matrices makes the permutation p too small.

What it reports

  • Tests: Unrelated dissimilarity matrices
r
The correlation between two dissimilarity matrices on the same objects, tested by permuting whole rows of one.
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.
pairs
The correlation between two dissimilarity matrices on the same objects, tested by permuting whole rows of one.
n_perm
How many independent units the analysis used; it sets precision and power.
partial
The Mantel correlation of two matrices holding a third constant.
q90
The correlation between two dissimilarity matrices on the same objects, tested by permuting whole rows of one.
q95
The correlation between two dissimilarity matrices on the same objects, tested by permuting whole rows of one.
q975
The correlation between two dissimilarity matrices on the same objects, tested by permuting whole rows of one.
q99
The correlation between two dissimilarity matrices on the same objects, tested by permuting whole rows of one.
missing_share
Values that were not recorded; how they went missing decides which fixes are safe.

Per group, level or term: class_r[<class>], class_p[<class>]

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 row permutations, so r and p match; vegan::mantel gives the same r (its p uses R's RNG).
  • The correlogram's classes are equal-width over the second matrix's range with Sturges' count; vegan::mantel.correlogram uses the same breaks but tests one-sided — ours are two-sided with the progressive Bonferroni correction.
Python

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

# Mantel test (and partial Mantel, correlogram)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method multivariate.mantel 1.0.1 · spec 44035ca11f6d727d
# Dataset: mv_mantel_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_mantel_guide.parquet", columns=["x1", "x2", "x3", "y1", "y2", "y3"])
n_input = len(df)
df = df.dropna(subset=["x1", "x2", "x3", "y1", "y2", "y3"])  # listwise deletion over the analysis columns
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, ["x1", "x2", "x3", "y1", "y2", "y3"])  # infinite values stop the run (registry/errors.yaml)

# %% Test
# Mantel test (Mantel 1967): correlation between the dissimilarities of two sets of variables measured on
# the same rows, p by permuting the rows (and columns) of the first matrix together. A third set gives the
# partial Mantel test (Smouse, Long & Sokal 1986); the correlogram tests distance classes of the second.
x_vars = ["x1", "x2", "x3"]
y_vars = ["y1", "y2", "y3"]
z_vars = []
x_metric = "euclidean"
y_metric = "euclidean"
x_transform = "none"
y_transform = "none"
method = "pearson"  # pearson | spearman
alternative = "greater"  # greater | two_sided | less
correlogram = False
n_classes = int(0)
seed = 42
n_perm = int(199)
alpha = 0.05
DIST_LABEL = {"euclidean": "Euclidean", "manhattan": "Manhattan", "bray": "Bray–Curtis", "jaccard": "Jaccard", "gower": "Gower"}
n = len(df)
if n > 3000:
    raise ValueError(f"The Mantel test uses n × n matrices; {n} rows is too many (at most 3000).")
if n < 5:
    cs.cs_error("CS_E_TOO_FEW_ROWS", what="The Mantel test", min=5, n=n)
A = mvdist.distance(mvdist.transform(df[x_vars].to_numpy(dtype=float), x_transform), x_metric)
B = mvdist.distance(mvdist.transform(df[y_vars].to_numpy(dtype=float), y_transform), y_metric)
C = mvdist.distance(mvdist.transform(df[z_vars].to_numpy(dtype=float), "standardize"), "euclidean") if z_vars else None
res = mvdist.mantel(A, B, C, method, alternative, n_perm, seed)
r, p = res["r"], res["p"]
cg = mvdist.correlogram(A, B, n_classes, method, n_perm, seed) if correlogram else None

# %% Assumptions
assumptions = [
    {"key": "linear", "label": "Linear relation between the dissimilarities", "status": "info",
     "detail": "The Mantel r measures a linear (Pearson) or monotone (Spearman) relation between pairwise dissimilarities, not between the raw variables."},
    {"key": "exchangeable", "label": "Exchangeable objects", "status": "info",
     "detail": "Rows are permuted as whole objects; with spatial or temporal structure in both matrices the permutation p is too small (Legendre, Fortin & Borcard 2015)."},
]

# %% Result
kind = "partial Mantel" if C is not None else "Mantel"
xs, ys = ", ".join(x_vars), ", ".join(y_vars)
cond = f", controlling for {', '.join(z_vars)}" if C is not None else ""
sig = p < alpha
direction = "positively" if r > 0 else "negatively"
summary = (f"The {kind} test ({'Spearman' if method == 'spearman' else 'Pearson'}) between the {DIST_LABEL[x_metric]} dissimilarities of {xs} "
           f"and the {DIST_LABEL[y_metric]} dissimilarities of {ys}{cond}: r_M = {r:.3f}, {cs.fmt_p(p)} ({n_perm} permutations) — "
           + (f"pairs of rows that differ more in one set differ {'more' if r > 0 else 'less'} in the other." if sig
              else "no evidence that the two sets of dissimilarities are related."))
values = {"r": r, "p": p, "n": n, "pairs": res["pairs"], "n_perm": n_perm, "partial": C is not None,
          "q90": float(res["quantiles"][0]), "q95": float(res["quantiles"][1]), "q975": float(res["quantiles"][2]), "q99": float(res["quantiles"][3])}
tables = [{"key": "null", "title": "Upper quantiles of the permutation distribution",
           "columns": [{"key": "q", "label": "Quantile", "type": "string"}, {"key": "value", "label": "r_M", "type": "number"}],
           "rows": [{"q": q, "value": float(v)} for q, v in zip(["90%", "95%", "97.5%", "99%"], res["quantiles"])]}]
charts = []
I, J = mvdist.pairs(n)
pick = np.unique(np.round(np.linspace(0, I.size - 1, min(I.size, 5000))).astype(int))
charts.append(cs.chart("pairs", "distance-distance", "Dissimilarity pairs", {
    "x": cs.col(f"{DIST_LABEL[y_metric]} dissimilarity of {ys}", B[I[pick], J[pick]]),
    "y": cs.col(f"{DIST_LABEL[x_metric]} dissimilarity of {xs}", A[I[pick], J[pick]])}, controls={"line": True}))
if cg is not None:
    rows = cg["classes"]
    for row in rows:
        values[f"class_r[{row['class']}]"] = row["r"]
        values[f"class_p[{row['class']}]"] = row["p_adj"]
    tables.append({"key": "correlogram", "title": f"Mantel correlogram over {cg['n_classes']} distance classes of {ys}",
                   "columns": [{"key": "class", "label": "Class", "type": "integer"}, {"key": "from", "label": "From", "type": "number"},
                               {"key": "to", "label": "To", "type": "number"}, {"key": "pairs", "label": "Pairs", "type": "integer"},
                               {"key": "r", "label": "r_M", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"},
                               {"key": "p_adj", "label": "Progressive p", "type": "pvalue"}],
                   "rows": [{k_: row[k_] for k_ in ("class", "from", "to", "pairs", "r", "p", "p_adj")} for row in rows]})
    ok = [row for row in rows if not np.isnan(row["r"])]
    charts.append(cs.chart("correlogram", "mantel-correlogram", f"Mantel correlogram: similarity of {xs} by distance class of {ys}", {
        "mid": cs.col(f"Distance class of {ys}", np.array([row["mid"] for row in ok])),
        "r": cs.col("Mantel r", np.array([row["r"] for row in ok])),
        "p": cs.col("Progressive p", np.array([row["p_adj"] for row in ok])),
        "pairs": cs.col("Pairs", np.array([row["pairs"] for row in ok], dtype=float))}, controls={"alpha": alpha}))
    first_pos = next((row for row in rows if not np.isnan(row["r"]) and row["r"] > 0 and row["p_adj"] < alpha), None)
    summary += (f" Correlogram: rows within the first significant class ({first_pos['from']:.3g}–{first_pos['to']:.3g}) are more similar than average."
                if first_pos else " Correlogram: no distance class is significantly more similar than average after the progressive correction.")
values["missing_share"] = n_dropped / n_input if n_input else 0.0
cs.publish({
    "method": "multivariate.mantel",
    "methodVersion": "1.0.1",
    "title": "Partial Mantel test" if C is not None else "Mantel test",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "apa": f"{kind} test, r_M = {r:.2f}, {cs.fmt_p(p)}",
    "statistics": [{"key": "r", "label": "r_M", "value": r}, {"key": "p", "label": "p", "value": p, "format": "p"},
                   {"key": "pairs", "label": "Pairs", "value": res["pairs"]}],
    "tables": tables,
    "effectSizes": [{"key": "r", "label": "Mantel r", "value": r, "method": "Correlation of the pairwise dissimilarities"}],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"{'Partial ' if C is not None else ''}Mantel r over {res['pairs']} pairs of rows; "
              + ("the third set is standardized Euclidean distance; " if C is not None else "")
              + f"{alternative.replace('_', '-')} p from {n_perm} row permutations of the first matrix (seed {seed})."
              + (" Correlogram classes split the second matrix's range into equal widths; p-values are two-sided with a progressive Bonferroni correction (Legendre & Legendre 2012)." if cg is not None else "")],
    "values": values,
    "charts": charts,
})
R

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

# Mantel test (and partial Mantel, correlogram)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method multivariate.mantel 1.0.1 · spec 44035ca11f6d727d
# Dataset: mv_mantel_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_mantel_guide.parquet", col_select = c("x1", "x2", "x3", "y1", "y2", "y3")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("x1", "x2", "x3", "y1", "y2", "y3")]), , 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("x1", "x2", "x3", "y1", "y2", "y3"))  # infinite values stop the run (registry/errors.yaml)

# %% Test
# Mantel test (Mantel 1967): correlation between the dissimilarities of two sets of variables measured on
# the same rows, p by permuting the rows (and columns) of the first matrix together. A third set gives the
# partial Mantel test (Smouse, Long & Sokal 1986); the correlogram tests distance classes of the second.
x_vars <- c("x1", "x2", "x3")
y_vars <- c("y1", "y2", "y3")
z_vars <- character(0)
x_metric <- "euclidean"
y_metric <- "euclidean"
x_transform <- "none"
y_transform <- "none"
method <- "pearson"  # pearson | spearman
alternative <- "greater"  # greater | two_sided | less
correlogram <- FALSE
n_classes <- as.integer(0)
seed <- 42
n_perm <- as.integer(199)
alpha <- 0.05
DIST_LABEL <- c(euclidean = "Euclidean", manhattan = "Manhattan", bray = "Bray–Curtis", jaccard = "Jaccard", gower = "Gower")
n <- nrow(df)
if (n > 3000) stop(sprintf("The Mantel test uses n × n matrices; %d rows is too many (at most 3000).", n))
if (n < 5) cs_error("CS_E_TOO_FEW_ROWS", what = "The Mantel test", min = 5, n = n)
A <- cs_mvd_distance(cs_mvd_transform(as.matrix(df[x_vars]), x_transform), x_metric)
B <- cs_mvd_distance(cs_mvd_transform(as.matrix(df[y_vars]), y_transform), y_metric)
C <- if (length(z_vars)) cs_mvd_distance(cs_mvd_transform(as.matrix(df[z_vars]), "standardize"), "euclidean") else NULL
res <- cs_mvd_mantel(A, B, C, method, alternative, n_perm, seed)
r <- res$r
p <- res$p
cg <- if (correlogram) cs_mvd_correlogram(A, B, n_classes, method, n_perm, seed) else NULL

# %% Assumptions
assumptions <- list(
  list(key = "linear", label = "Linear relation between the dissimilarities", status = "info",
       detail = "The Mantel r measures a linear (Pearson) or monotone (Spearman) relation between pairwise dissimilarities, not between the raw variables."),
  list(key = "exchangeable", label = "Exchangeable objects", status = "info",
       detail = "Rows are permuted as whole objects; with spatial or temporal structure in both matrices the permutation p is too small (Legendre, Fortin & Borcard 2015).")
)

# %% Result
kind <- if (!is.null(C)) "partial Mantel" else "Mantel"
xs <- paste(x_vars, collapse = ", ")
ys <- paste(y_vars, collapse = ", ")
cond <- if (!is.null(C)) paste0(", controlling for ", paste(z_vars, collapse = ", ")) else ""
summary <- paste0(sprintf("The %s test (%s) between the %s dissimilarities of %s and the %s dissimilarities of %s%s: r_M = %.3f, %s (%d permutations) — ",
                          kind, if (method == "spearman") "Spearman" else "Pearson", DIST_LABEL[[x_metric]], xs, DIST_LABEL[[y_metric]], ys, cond, r, cs_fmt_p(p), n_perm),
                  if (p < alpha) sprintf("pairs of rows that differ more in one set differ %s in the other.", if (r > 0) "more" else "less")
                  else "no evidence that the two sets of dissimilarities are related.")
values <- list(r = r, p = p, n = n, pairs = res$pairs, n_perm = n_perm, partial = !is.null(C),
               q90 = res$quantiles[1], q95 = res$quantiles[2], q975 = res$quantiles[3], q99 = res$quantiles[4])
tables <- list(list(key = "null", title = "Upper quantiles of the permutation distribution",
                    columns = list(list(key = "q", label = "Quantile", type = "string"), list(key = "value", label = "r_M", type = "number")),
                    rows = data.frame(q = c("90%", "95%", "97.5%", "99%"), value = res$quantiles)))
pr <- cs_mvd_pairs(n)
pick <- unique(round(seq(1, length(pr$i), length.out = min(length(pr$i), 5000))))
charts <- list(cs_chart("pairs", "distance-distance", "Dissimilarity pairs", list(
  x = cs_col(sprintf("%s dissimilarity of %s", DIST_LABEL[[y_metric]], ys), B[cbind(pr$i[pick], pr$j[pick])]),
  y = cs_col(sprintf("%s dissimilarity of %s", DIST_LABEL[[x_metric]], xs), A[cbind(pr$i[pick], pr$j[pick])])), controls = list(line = TRUE)))
if (!is.null(cg)) {
  rows <- cg$classes
  for (row in rows) {
    values[[sprintf("class_r[%d]", as.integer(row$class))]] <- row$r
    values[[sprintf("class_p[%d]", as.integer(row$class))]] <- row$p_adj
  }
  tables[[2]] <- list(key = "correlogram", title = sprintf("Mantel correlogram over %d distance classes of %s", as.integer(cg$n_classes), ys),
    columns = list(list(key = "class", label = "Class", type = "integer"), list(key = "from", label = "From", type = "number"),
                   list(key = "to", label = "To", type = "number"), list(key = "pairs", label = "Pairs", type = "integer"),
                   list(key = "r", label = "r_M", type = "number"), list(key = "p", label = "p", type = "pvalue"),
                   list(key = "p_adj", label = "Progressive p", type = "pvalue")),
    rows = lapply(rows, function(row) row[c("class", "from", "to", "pairs", "r", "p", "p_adj")]))
  ok <- Filter(function(row) !is.nan(row$r), rows)
  charts[[2]] <- cs_chart("correlogram", "mantel-correlogram", sprintf("Mantel correlogram: similarity of %s by distance class of %s", xs, ys), list(
    mid = cs_col(sprintf("Distance class of %s", ys), vapply(ok, `[[`, 0, "mid")),
    r = cs_col("Mantel r", vapply(ok, `[[`, 0, "r")),
    p = cs_col("Progressive p", vapply(ok, `[[`, 0, "p_adj")),
    pairs = cs_col("Pairs", as.numeric(vapply(ok, `[[`, 0, "pairs")))), controls = list(alpha = alpha))
  first_pos <- Find(function(row) !is.nan(row$r) && row$r > 0 && row$p_adj < alpha, rows)
  summary <- paste(summary, if (!is.null(first_pos))
    sprintf("Correlogram: rows within the first significant class (%s–%s) are more similar than average.", format(signif(first_pos$from, 3)), format(signif(first_pos$to, 3)))
    else "Correlogram: no distance class is significantly more similar than average after the progressive correction.")
}
values$missing_share <- if (n_input > 0) n_dropped / n_input else 0
cs_publish(list(
  method = "multivariate.mantel",
  methodVersion = "1.0.1",
  title = if (!is.null(C)) "Partial Mantel test" else "Mantel test",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = summary,
  apa = sprintf("%s test, r_M = %.2f, %s", kind, r, cs_fmt_p(p)),
  statistics = list(list(key = "r", label = "r_M", value = r), list(key = "p", label = "p", value = p, format = "p"),
                    list(key = "pairs", label = "Pairs", value = res$pairs)),
  tables = tables,
  effectSizes = list(list(key = "r", label = "Mantel r", value = r, method = "Correlation of the pairwise dissimilarities")),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(paste0(sprintf("%sMantel r over %d pairs of rows; ", if (!is.null(C)) "Partial " else "", as.integer(res$pairs)),
                      if (!is.null(C)) "the third set is standardized Euclidean distance; " else "",
                      sprintf("%s p from %d row permutations of the first matrix (seed %d).", sub("_", "-", alternative), n_perm, as.integer(seed)),
                      if (!is.null(cg)) " Correlogram classes split the second matrix's range into equal widths; p-values are two-sided with a progressive Bonferroni correction (Legendre & Legendre 2012)." else "")),
  values = values,
  charts = charts
))

Sources

  • Mantel, N. (1967). The detection of disease clustering and a generalized regression approach. Cancer Research, 27, 209–220.
  • Smouse, P. E., Long, J. C., & Sokal, R. R. (1986). Multiple regression and correlation extensions of the Mantel test of matrix correspondence. Systematic Zoology, 35, 627–632.
  • Legendre, P., & Legendre, L. (2012). Numerical Ecology (3rd ed.), §10.5 and §13.1.5. Elsevier.
  • Legendre, P., Fortin, M.-J., & Borcard, D. (2015). Should the Mantel test be used in spatial analysis? Methods in Ecology and Evolution, 6, 1239–1247.

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