Skip to content

BCompare groups · permutation.two_sample

Permutation test (two independent groups)

Is the difference in means larger than chance relabeling of the groups would produce?

Compares the observed difference in means with its distribution over relabelings of the two groups: exact (all splits) when there are at most 200,000, otherwise a Monte Carlo sample of permutations drawn from a shared seeded stream, so Python and R give the same p-value. No distributional assumptions beyond exchangeability under H0.

Verified in Python and R Python and R agree to 10 decimals Seeded

A real result

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

Permutation testRecorded · Python and R agreeRecorded 2026-11-25 · 13 values compared
R

permutation test, Δ = −15.64, p = .006

Mean difference (A − B)
−15.636
p
.006
Permutations
924

Effect size

  • Cohen's d −1.957

Plots

after by sectionHow do groups compare in shape, summary and individual observations at once?
View data
sectionafter
A45.783
A46.797
A57.078
A55.415
A64.214
A61.554
B60.646
B67.486
B72.285
B69.622
B68.603
B86.017

Assumptions

  • Exchangeability — Variance ratio 1.24.
  • Difference = A − B; exact (all splits); alternative: two-sided. p = count / total.
Python

permutation test, Δ = −15.64, p = .006

Mean difference (A − B)
−15.636
p
.006
Permutations
924

Effect size

  • Cohen's d −1.957

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

Assumptions

  • Exchangeability — Variance ratio 1.24.
  • Difference = A − B; exact (all splits); alternative: two-sided. p = count / total.

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

  • Exact smallscores · group: section · outcome: after
  • Monte carlotoothgrowth · group: supp · outcome: len
  • Boolean greatermtcars · group: manual · outcome: mpg
  • Degenerate constantscores · group: section · outcome: after
  • Degenerate single levelscores · group: section · outcome: after

In the guides

Where it sits in the decision guides

  • Two independent groups (continuous): Student / Welch t, Mann–Whitney U · Statistics Guide · B — Compare groups
  • Robust, permutation and exact methods · Statistics Guide · Step 3 — If assumptions are violated
  • Non-parametric alternatives · Statistics Guide · Additional considerations

What you need

Outcomenumeric · 1 column
The numeric variable you are analyzing.
Groupscategorical / boolean · 1 column · 2–2 levels
The column whose levels define the groups to compare.

Choices you make

hypothesis

Alternative hypothesisdefault two-sided

Which direction counts as evidence. Keep two-sided unless you fixed the direction before seeing the data.

  • Means differ (≠)(default) — Tests for a difference in means in either direction; keep it unless you fixed a direction before seeing the data.
  • First group higher (>) — Tests only for the first group being higher; pick it only if you fixed this direction before seeing the data.
  • First group lower (<) — Tests only for the first group being lower; pick it only if you fixed this direction before seeing the data.

options

Monte Carlo permutationsdefault 9999

Used only when there are more than 200,000 possible splits.

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.

  • Exchangeability

    Under H0 the group labels are interchangeable (similar spreads); with very different variances prefer Welch's test or Brunner–Munzel.

What it reports

  • Tests: Difference in means (permutation)
diff
One group's mean minus another's, in the outcome's own units.
p
How surprising your data would be if the null hypothesis were true, as a probability.
n_perm
How many independent units the analysis used; it sets precision and power.
exact
True when every possible relabeling was enumerated, giving an exact p-value; false when random permutations were drawn.
count
Builds the null distribution by reshuffling group labels, so it needs no distributional assumption.
mean_1
The sum divided by the count; the balance point of the data, pulled by extreme values.
mean_2
The sum divided by the count; the balance point of the data, pulled by extreme values.
n_1
How many independent units the analysis used; it sets precision and power.
n_2
How many independent units the analysis used; it sets precision and power.
cohens_d
A difference in means expressed in standard deviations.
level_1
Which group counts as first (or treated, or positive) decides the sign of differences and ratios on the card.
level_2
Which group counts as first (or treated, or positive) decides the sign of differences and ratios on the card.
missing_share
Values that were not recorded; how they went missing decides which fixes are safe.

Python and R

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

Default traps between the two languages

  • Monte Carlo permutations come from the shared Wichmann–Hill stream (codesplash.stats.rng ↔ cs_rng), so both engines evaluate the same permutations and count identically.
Python

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

# Permutation test (two independent groups)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method permutation.two_sample 1.0.2 · spec fa059dd1e42afbd6
# Dataset: scores (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 permutation

# %% Data
df = pd.read_parquet("tests/parity/fixtures/scores.parquet", columns=["after", "section"])
n_input = len(df)
df["section"] = pd.Categorical(df["section"], categories=["A", "B"])  # stored level order
df = df.dropna(subset=["after", "section"])  # listwise deletion over the analysis columns
df["section"] = df["section"].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, ["after", "section"])  # infinite values stop the run (registry/errors.yaml)

# %% Two samples (independent groups or paired measurements, from the bound roles)
y = "after"
g = "section"
levels = [str(x) for x in df[g].cat.categories]
if len(levels) != 2:
    cs.cs_error("CS_E_GROUP_COUNT", column=g, expected=2, k=len(levels))
x1 = df.loc[df[g] == df[g].cat.categories[0], y].to_numpy(dtype=float)
x2 = df.loc[df[g] == df[g].cat.categories[1], y].to_numpy(dtype=float)
design, label_1, label_2 = "independent", levels[0], levels[1]

# %% Test
alternative = "two-sided"
seed = 42  # shared Wichmann–Hill stream: R draws the same permutations
r = permutation.two_sample(x1, x2, alternative=alternative, max_exact=200000, b=int(9999), seed=seed)
n1, n2 = len(x1), len(x2)
sp = np.sqrt(((n1 - 1) * np.var(x1, ddof=1) + (n2 - 1) * np.var(x2, ddof=1)) / (n1 + n2 - 2))
# Cohen's d is undefined when neither sample varies (pooled SD 0): published as null, as in R.
no_spread = len(np.unique(x1)) < 2 and len(np.unique(x2)) < 2
d = None if no_spread else float(r["diff"] / sp)

# %% Assumptions
# A sample with no spread has exactly zero variance (np.var can leave rounding noise), as in R.
v1 = 0.0 if len(np.unique(x1)) < 2 else np.var(x1, ddof=1)
v2 = 0.0 if len(np.unique(x2)) < 2 else np.var(x2, ddof=1)
ratio = max(v1, v2) / min(v1, v2) if min(v1, v2) > 0 else float("inf")
assumptions = [{"key": "exchangeability", "label": "Exchangeability", "status": "warn" if ratio > 4 else "pass",
                "detail": f"Variance ratio {ratio:.2f}" + ("; very different spreads make the labels non-exchangeable (consider Welch's test)." if ratio > 4 else ".")}]

# %% Result
values = {"diff": r["diff"], "p": r["p"], "n_perm": r["n_perm"], "exact": r["exact"], "count": r["count"], "mean_1": float(x1.mean()),
          "mean_2": float(x2.mean()), "n_1": n1, "n_2": n2, "cohens_d": d, "level_1": label_1, "level_2": label_2}
chart_rows = np.unique(np.round(np.linspace(0, len(df) - 1, min(len(df), 5000))).astype(int))
how = "exact (all splits)" if r["exact"] else f"{r['n_perm']} Monte Carlo permutations, seed {seed}"
values["missing_share"] = n_dropped / n_input if n_input else 0.0  # consult-a-statistician input
cs.publish({
    "method": "permutation.two_sample",
    "methodVersion": "1.0.2",
    "title": "Permutation test",
    "engine": cs.engine_info("pandas", "numpy"),
    "n": n1 + n2,
    "summary": f"Difference in means {r['diff']:.3f}; permutation {cs.fmt_p(r['p'])} ({how}).",
    "apa": f"permutation test, Δ = {cs.fmt_num(r['diff'])}, {cs.fmt_p(r['p'])}",
    "statistics": [{"key": "diff", "label": f"Mean difference ({label_1} − {label_2})", "value": r["diff"]},
                   {"key": "p", "label": "p", "value": r["p"], "format": "p"},
                   {"key": "n_perm", "label": "Permutations", "value": r["n_perm"], "format": "integer"}],
    "effectSizes": [{"key": "cohens_d", "label": "Cohen's d", "value": d, "method": "pooled SD"}],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Difference = {label_1} − {label_2}; {how}; alternative: {alternative}. "
              + ("p = count / total." if r["exact"] else "p = (count + 1) / (permutations + 1).")],
    "values": values,
    "charts": [cs.chart("distribution", "raincloud", f"{y} by {g}", {
        "y": cs.col(y, df[y].to_numpy(dtype=float)[chart_rows]),
        "group": cs.col(g, df[g].astype(str).to_numpy()[chart_rows], levels=levels)})],
})
R

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

# Permutation test (two independent groups)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method permutation.two_sample 1.0.2 · spec fa059dd1e42afbd6
# Dataset: scores (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/scores.parquet", col_select = c("after", "section")))
n_input <- nrow(df)
df[["section"]] <- factor(df[["section"]], levels = c("A", "B"))  # stored level order
df <- df[stats::complete.cases(df[c("after", "section")]), , 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("after", "section"))  # infinite values stop the run (registry/errors.yaml)

# %% Two samples (independent groups or paired measurements, from the bound roles)
y <- "after"
g <- "section"
levels_g <- levels(df[[g]])
if (length(levels_g) != 2) cs_error("CS_E_GROUP_COUNT", column = g, expected = 2, k = length(levels_g))
x1 <- df[[y]][df[[g]] == levels_g[1]]
x2 <- df[[y]][df[[g]] == levels_g[2]]
design <- "independent"
label_1 <- levels_g[1]
label_2 <- levels_g[2]

# %% Test
alternative <- "two-sided"
seed <- 42  # shared Wichmann-Hill stream: Python draws the same permutations
r <- cs_perm_two_sample(x1, x2, alternative = alternative, max_exact = 200000, b = 9999, seed = seed)
n1 <- length(x1)
n2 <- length(x2)
sp <- sqrt(((n1 - 1) * var(x1) + (n2 - 1) * var(x2)) / (n1 + n2 - 2))
# Cohen's d is undefined when neither sample varies (pooled SD 0): published as null.
no_spread <- length(unique(x1)) < 2 && length(unique(x2)) < 2
d <- if (no_spread) NA_real_ else r$diff / sp

# %% Assumptions
v1 <- var(x1)
v2 <- var(x2)
ratio <- if (min(v1, v2) > 0) max(v1, v2) / min(v1, v2) else Inf
assumptions <- list(list(key = "exchangeability", label = "Exchangeability", status = if (ratio > 4) "warn" else "pass",
                         detail = paste0(sprintf("Variance ratio %.2f", ratio),
                                         if (ratio > 4) "; very different spreads make the labels non-exchangeable (consider Welch's test)." else ".")))

# %% Result
values <- list(diff = r$diff, p = r$p, n_perm = r$n_perm, exact = r$exact, count = r$count, mean_1 = mean(x1), mean_2 = mean(x2),
               n_1 = n1, n_2 = n2, cohens_d = d, level_1 = label_1, level_2 = label_2)
chart_rows <- unique(round(seq(1, nrow(df), length.out = min(nrow(df), 5000))))
values$missing_share <- if (n_input > 0) n_dropped / n_input else 0  # consult-a-statistician input
how <- if (r$exact) "exact (all splits)" else sprintf("%d Monte Carlo permutations, seed %d", as.integer(r$n_perm), as.integer(seed))
cs_publish(list(
  method = "permutation.two_sample",
  methodVersion = "1.0.2",
  title = "Permutation test",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n1 + n2,
  summary = sprintf("Difference in means %.3f; permutation %s (%s).", r$diff, cs_fmt_p(r$p), how),
  apa = sprintf("permutation test, Δ = %s, %s", cs_fmt_num(r$diff), cs_fmt_p(r$p)),
  statistics = list(list(key = "diff", label = sprintf("Mean difference (%s − %s)", label_1, label_2), value = r$diff),
                    list(key = "p", label = "p", value = r$p, format = "p"),
                    list(key = "n_perm", label = "Permutations", value = r$n_perm, format = "integer")),
  effectSizes = list(list(key = "cohens_d", label = "Cohen's d", value = d, method = "pooled SD")),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(paste0(sprintf("Difference = %s − %s; %s; alternative: %s. ", label_1, label_2, how, alternative),
                      if (r$exact) "p = count / total." else "p = (count + 1) / (permutations + 1).")),
  values = values,
  charts = list(cs_chart("distribution", "raincloud", sprintf("%s by %s", y, g),
                         list(y = cs_col(y, df[[y]][chart_rows]), group = cs_col(g, as.character(df[[g]][chart_rows]), levels = levels_g))))
))

Sources

  • Good, P. (2005). Permutation, parametric, and bootstrap tests of hypotheses (3rd ed.). Springer.
  • Phipson, B., & Smyth, G. K. (2010). Permutation p-values should never be zero. Statistical Applications in Genetics and Molecular Biology, 9(1).

From the CodeSplash method registry · permutation.two_sample v1.0.2.