BMultivariate · multivariate.anosim
ANOSIM (analysis of similarities)
Are rows more alike within groups than between them, judged by ranked dissimilarities?
ANOSIM ranks every dissimilarity between rows and compares the mean rank between groups with the mean rank within groups: R near 0 means no separation, near 1 complete separation. The p-value permutes the group labels. Widely used for community data; like PERMANOVA it also reacts to groups that differ only in spread.
A real result
Example “Guide euclidean”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
ANOSIM (Euclidean), R = 0.12, p = .005
- R
- 0.1182
- p
- .005
Effect size
- ANOSIM R 0.1182
Plots
View data
| group | PCoA 1 (42.4%) | PCoA 2 (32.5%) |
|---|---|---|
| g1 | 1.880 | −0.0590 |
| g1 | −1.612 | 0.8910 |
| g1 | 1.852 | 0.2849 |
| g1 | 1.182 | 0.9049 |
| g1 | 0.6558 | 0.7322 |
| g1 | −1.723 | 2.557 |
| g1 | −0.3537 | 1.066 |
| g1 | 0.8733 | 1.373 |
| g1 | −1.190 | −0.0974 |
| g1 | −1.994 | −0.0357 |
| g1 | 2.363 | 1.065 |
| g1 | −0.9171 | 0.3980 |
| g1 | 1.105 | 0.4423 |
| g1 | −0.8731 | 0.2165 |
| g1 | 1.609 | 3.095 |
| g1 | 0.7412 | −0.9501 |
| g1 | 1.794 | −0.2277 |
| g1 | 1.202 | 0.0360 |
| g1 | 0.8136 | 1.379 |
| g1 | 0.6387 | −0.6940 |
| g1 | −0.6997 | 0.1242 |
| g1 | 0.4424 | 0.5991 |
| g1 | 0.2818 | 1.578 |
| g1 | 1.449 | −0.7876 |
| g1 | 0.5212 | −0.4453 |
| g1 | 0.2217 | −1.750 |
| g1 | 2.778 | −1.161 |
| g1 | −1.653 | −0.0826 |
| g1 | 1.813 | −0.1413 |
| g1 | 1.168 | −0.9665 |
| g1 | 0.9167 | 1.327 |
| g1 | 1.130 | 0.4960 |
| g1 | −0.4198 | 0.8517 |
| g1 | 0.3646 | −0.3902 |
| g1 | 0.4888 | 0.4014 |
| g1 | 1.132 | −0.9397 |
| g1 | −0.8284 | 0.1889 |
| g1 | −1.268 | 0.8131 |
| g1 | −1.258 | −1.108 |
| g1 | 0.3973 | 1.515 |
| g2 | 0.3005 | −1.929 |
| g2 | 2.515 | −1.324 |
| g2 | −0.2758 | 0.0576 |
| g2 | 0.8521 | −0.7303 |
| g2 | −0.2571 | 1.649 |
| g2 | −1.075 | −0.8621 |
| g2 | 1.336 | 0.2787 |
| g2 | 0.1976 | 0.4148 |
| g2 | −1.410 | −0.4676 |
| g2 | −0.5506 | −1.262 |
| g2 | 0.4851 | −0.0900 |
| g2 | −0.9148 | −2.405 |
| g2 | −0.6339 | −0.7328 |
| g2 | −1.124 | 0.1816 |
| g2 | 0.1908 | −0.2489 |
| g2 | −1.143 | −0.1104 |
| g2 | 0.4909 | 1.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 — ANOSIM reacts to differences in spread as well as location (Anderson & Walsh 2013); run PERMDISP to tell them apart.
- Exchangeable rows — Labels were permuted freely; give blocks or sites as strata so permutations respect the design.
Mean rank of the dissimilarities
| Pairs | n | Mean rank |
|---|---|---|
| Between groups | — | 2121.47 |
| Within g1 | 40 | 2081.67 |
| Within g2 | 50 | 1759.49 |
- Euclidean dissimilarity of the variables, ranked (ties get mid-ranks); p from 199 label permutations on the shared seeded stream (seed 42).
ANOSIM (Euclidean), R = 0.12, p = .005
- R
- 0.1182
- p
- .005
Effect size
- ANOSIM R 0.1182
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Similar spread across groups — ANOSIM reacts to differences in spread as well as location (Anderson & Walsh 2013); run PERMDISP to tell them apart.
- Exchangeable rows — Labels were permuted freely; give blocks or sites as strata so permutations respect the design.
Mean rank of the dissimilarities
| Pairs | n | Mean rank |
|---|---|---|
| Between groups | — | 2121.47 |
| Within g1 | 40 | 2081.67 |
| Within g2 | 50 | 1759.49 |
- Euclidean dissimilarity of the variables, ranked (ties get mid-ranks); p from 199 label permutations on the shared seeded stream (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 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
- Mite stratamv_mite · group: Topo · strata: Shrub · variables: Brachy, PHTH, HPAV, RARD, SSTR, Protopl, MEGR, MPRO, TVIE, HMIN, HMIN2, NPRA, TVEL, ONOV, SUCT, LCIL
- 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 ranked.
- 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 bray
How unlike two rows are; only the ranks of the dissimilarities matter.
- Euclidean — Straight-line distance; standardize first when variables have different units.
- Manhattan (city block) — Sum of absolute differences.
- Bray–Curtis(default) — Σ|x − y| / Σ(x + y) for non-negative counts or abundances; the usual choice for ANOSIM.
- 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
- 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
ANOSIM confounds location and spread; PERMDISP separates them.
Exchangeable rows
Rows must be exchangeable under the null; give blocks or sites as strata.
What it reports
- Tests: No separation of the groups
- r
- Compares ranked dissimilarities between groups with those within; R from −1 to 1, near 0 for no separation.
- p
- How surprising your data would be if the null hypothesis were true, as a probability.
- mean_rank_between
- Mean rank of the dissimilarities between rows in different groups. Above the within-group mean rank means groups separate.
- mean_rank_within
- Mean rank of the dissimilarities between rows in the same group. Below the between-group mean rank means groups separate.
- 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: mean_rank[<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; mid-ranks (scipy.stats.rankdata ↔ rank(ties = 'average')) and the shared Wichmann–Hill permutations make R and p identical.
The exact script CodeSplash ran for example “Guide euclidean” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# ANOSIM (analysis of similarities)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method multivariate.anosim 1.0.1 · spec c4a43095b19ce3fd
# 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
# ANOSIM (Clarke 1993): R = (r̄_between − r̄_within) / (M/2) on mid-ranks of the M dissimilarities,
# p by permuting the group labels (within strata when given).
alpha = 0.05
res = mvdist.anosim(D, codes, k, n_perm, seed, strata)
r, p = res["r"], res["p"]
if r < 0:
shape = "negative R: rows are more alike between groups than within them (check the grouping or the data)."
elif r < 0.25:
shape = "the groups barely separate (R < 0.25)."
elif r < 0.5:
shape = "the groups overlap but differ (0.25 ≤ R < 0.5)."
elif r < 0.75:
shape = "the groups are clearly separated with some overlap (0.5 ≤ R < 0.75)."
else:
shape = "the groups are well separated (R ≥ 0.75)."
# %% Assumptions
assumptions = [
{"key": "dispersion", "label": "Similar spread across groups", "status": "info",
"detail": "ANOSIM reacts to differences in spread as well as location (Anderson & Walsh 2013); run PERMDISP to tell them apart."},
{"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"ANOSIM on the ranked {dist_text} ({', '.join(variables)}): R = {r:.3f}, {cs.fmt_p(p)} ({n_perm} permutations) — "
+ (f"the {k} groups of {g} differ; " if p < alpha else f"no evidence that the {k} groups of {g} differ; ") + shape)
values = {"r": r, "p": p, "mean_rank_between": res["mean_rank_between"], "mean_rank_within": res["mean_rank_within"], "k": k, "n": n,
"n_perm": n_perm}
for lv, mr in zip(levels, res["group_mean_rank"]):
values[f"mean_rank[{lv}]"] = float(mr)
values["missing_share"] = n_dropped / n_input if n_input else 0.0
rows = [{"group": "Between groups", "n": None, "rank": res["mean_rank_between"]}]
rows += [{"group": f"Within {lv}", "n": int(m), "rank": float(mr)} for lv, m, mr in zip(levels, group_n, res["group_mean_rank"])]
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.anosim",
"methodVersion": "1.0.1",
"title": "ANOSIM",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": f"ANOSIM ({DIST_LABEL[metric]}), R = {r:.2f}, {cs.fmt_p(p)}",
"statistics": [{"key": "r", "label": "R", "value": r}, {"key": "p", "label": "p", "value": p, "format": "p"}],
"tables": [{"key": "ranks", "title": "Mean rank of the dissimilarities",
"columns": [{"key": "group", "label": "Pairs", "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
{"key": "rank", "label": "Mean rank", "type": "number"}],
"rows": rows}],
"effectSizes": [{"key": "r", "label": "ANOSIM R", "value": r, "method": "(r̄_B − r̄_W) / (M/2); 0 = no separation, 1 = complete"}],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"{dist_text}, ranked (ties get mid-ranks); p from {n_perm} label permutations on the shared seeded stream (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})],
})
The exact script CodeSplash ran for example “Guide euclidean” · R version 4.5.1 (2025-06-13)
# ANOSIM (analysis of similarities)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method multivariate.anosim 1.0.1 · spec c4a43095b19ce3fd
# 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
# ANOSIM (Clarke 1993): R = (rbar_between - rbar_within) / (M/2) on mid-ranks of the M dissimilarities,
# p by permuting the group labels (within strata when given).
alpha <- 0.05
res <- cs_mvd_anosim(D, codes, k, n_perm, seed, strata)
r <- res$r
p <- res$p
shape <- if (r < 0) "negative R: rows are more alike between groups than within them (check the grouping or the data)." else
if (r < 0.25) "the groups barely separate (R < 0.25)." else
if (r < 0.5) "the groups overlap but differ (0.25 ≤ R < 0.5)." else
if (r < 0.75) "the groups are clearly separated with some overlap (0.5 ≤ R < 0.75)." else
"the groups are well separated (R ≥ 0.75)."
# %% Assumptions
assumptions <- list(
list(key = "dispersion", label = "Similar spread across groups", status = "info",
detail = "ANOSIM reacts to differences in spread as well as location (Anderson & Walsh 2013); run PERMDISP to tell them apart."),
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("ANOSIM on the ranked %s (%s): R = %.3f, %s (%d permutations) — ", dist_text, paste(variables, collapse = ", "), r, cs_fmt_p(p), n_perm),
if (p < alpha) sprintf("the %d groups of %s differ; ", k, g) else sprintf("no evidence that the %d groups of %s differ; ", k, g),
shape)
values <- list(r = r, p = p, mean_rank_between = res$mean_rank_between, mean_rank_within = res$mean_rank_within, k = k, n = n, n_perm = n_perm)
for (i in seq_len(k)) values[[sprintf("mean_rank[%s]", levels_g[i])]] <- res$group_mean_rank[i]
values$missing_share <- if (n_input > 0) n_dropped / n_input else 0
rows <- c(list(list(group = "Between groups", n = NULL, rank = res$mean_rank_between)),
lapply(seq_len(k), function(i) list(group = paste("Within", levels_g[i]), n = as.integer(group_n[i]), rank = res$group_mean_rank[i])))
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.anosim",
methodVersion = "1.0.1",
title = "ANOSIM",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = sprintf("ANOSIM (%s), R = %.2f, %s", DIST_LABEL[[metric]], r, cs_fmt_p(p)),
statistics = list(list(key = "r", label = "R", value = r), list(key = "p", label = "p", value = p, format = "p")),
tables = list(list(key = "ranks", title = "Mean rank of the dissimilarities",
columns = list(list(key = "group", label = "Pairs", type = "string"), list(key = "n", label = "n", type = "integer"),
list(key = "rank", label = "Mean rank", type = "number")),
rows = rows)),
effectSizes = list(list(key = "r", label = "ANOSIM R", value = r, method = "(r̄_B − r̄_W) / (M/2); 0 = no separation, 1 = complete")),
assumptions = assumptions,
warnings = warnings,
notes = list(paste0(sprintf("%s, ranked (ties get mid-ranks); p from %d label permutations on the shared seeded stream (seed %d).", dist_text, 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
- Clarke, K. R. (1993). Non-parametric multivariate analyses of changes in community structure. Australian Journal of Ecology, 18, 117–143.
- 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.anosim v1.0.1.