Permutation tests: let the design make the null
Randomization gives you a reference distribution with no formula at all. Learn what makes a permutation test valid and how the Monte Carlo version works.
What runs in CodeSplash
- Permutation test (two independent groups) Verified in Python and R
You will be able to
- State what the permutation null assumes
- Compute an exact p-value by counting arrangements
- Explain why the Monte Carlo p-value adds one to the count
Read first
The idea
ReadIf the group labels carry no information, every way of assigning them was equally likely. Compute your statistic for each arrangement and you have its exact null distribution, derived from the study itself.
What this needs is exchangeabilityExchangeabilityUnder the null, any relabeling of the data is as likely as the one observed. Permutation tests rest on this.: swapping labels must not change the joint distribution under the null. Random assignment gives you that by design. Observational groups only approximate it.
Count the arrangements
PredictPredict first
Two sections of six students each. How many ways are there to choose which six students carry the label A?
Make your guess between 100 and 2000 arrangements, then reveal.
Reveal
= 924. Few enough to enumerate every one, so this test is exact.
Read the exact result
Readpermutation test, Δ = −15.64, p = .006
- Mean difference (A − B)
- −15.636
- p
- .006
- Permutations
- 924
Effect size
- Cohen's d −1.957
Plots
View data
| section | after |
|---|---|
| A | 45.783 |
| A | 46.797 |
| A | 57.078 |
| A | 55.415 |
| A | 64.214 |
| A | 61.554 |
| B | 60.646 |
| B | 67.486 |
| B | 72.285 |
| B | 69.622 |
| B | 68.603 |
| B | 86.017 |
Assumptions
- Exchangeability — Variance ratio 1.24.
- Difference = A − B; exact (all splits); alternative: two-sided. p = count / total.
The exact R script · R 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))))
))
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.
The exact Python script · Python 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)})],
})
The observed difference was −15.6. Exactly 6 of the 924 arrangements gave a difference at least that large in either direction:
which is p = .006.
Too many to count
ReadWith 30 animals in each group there are about arrangements. CodeSplash samples them instead, here 1,999 random shuffles from one shared random stream, so Python and R reach the identical count:
130 shuffles were at least as extreme, so p = .066. The +1 counts the real data as one arrangement, which keeps the test valid and means p can never be exactly 0.
Shuffle it yourself
ExploreRun shuffles in batches and watch the pile of differences build up. Then break it: what happens to the distribution when the outcomes in the two groups have very different spreads?
BExplorable · Permutation shuffler
Could a difference this large come from shuffling the labels alone?
Shuffle the labels a thousand times. How often will the shuffled difference be as large as the real one?
Data
Statistic
+30 on the last value of the second group.
Commit your prediction above to see the result
Make your prediction to see the result.
Check your understanding
CheckpointCheck yourself
You ran 999 random shuffles and none matched the observed difference. What is the Monte Carlo p-value?
Show the answer
Answer: 0.001
(0 + 1) / (999 + 1) = 0.001. It can't be zero: the observed arrangement is one of the possibilities.
Check yourself
Which assumption does a two-group permutation test rely on?
Show the answer
Answer: c
No distributional form is needed, but the labels must be exchangeable. With paired or clustered data, shuffle within pairs or clusters instead.
Check yourself
Students are clustered in classrooms, and whole classrooms got the treatment. How should you permute?
Show the answer
Answer: b
Permute at the level the treatment was assigned. Shuffling students breaks the clustering and understates the variability.
Do it in CodeSplash
In the appSet Monte Carlo permutations for larger datasets; small tables are enumerated in full. The seed is stored with the analysis, so reruns match in both engines.
import numpy as np
import pandas as pd
from scipy import stats
df = pd.read_csv("scores.csv")
a = df.loc[df["section"] == "A", "after"]
b = df.loc[df["section"] == "B", "after"]
res = stats.permutation_test(
(a, b),
lambda x, y: np.mean(x) - np.mean(y),
permutation_type="independent",
n_resamples=np.inf, # enumerate every arrangement
alternative="two-sided",
)
print(res.statistic, res.pvalue)df <- read.csv("scores.csv")
y <- df$after
idx <- combn(length(y), sum(df$section == "A"))
obs <- with(df, mean(after[section == "A"]) - mean(after[section == "B"]))
d <- apply(idx, 2, function(i) mean(y[i]) - mean(y[-i]))
mean(abs(d) >= abs(obs) - 1e-12)Recap
Recap- Permutation tests build the null by relabeling, and rely on exchangeable labels, not on a distribution.
- Small designs can be enumerated exactly; larger ones use (count + 1) / (B + 1).
- Permute at the level of the randomization.
Concepts in this lesson