Skip to content

A permutation test by hand

Work out a p-value with nothing but counting. Six numbers are enough to see where every p-value comes from.

Introductory ~11 min8 steps

What runs in CodeSplash

You will be able to

  • Carry out a small permutation test by counting arrangements
  • State what the shuffle assumes when the null hypothesis is true
  • Explain why a small study can't reach a small p-value

Read first

01

A tiny experiment

Read

Six plants, three of them treated, were chosen at random. Their growth:

TreatedControl
7, 9, 112, 4, 6

The treated mean is 9, the control mean is 4, and the observed difference is 5.

Suppose the null hypothesisNull hypothesisThe default claim a test tries to find evidence against, usually "no difference" or "no effect". is true and treatment does nothing. Each plant would have grown the same under either label, so the labels are arbitrary. Any 3 of the 6 could equally have been called "treated".

02

How many arrangements?

Predict

Predict first

How many ways can you choose which 3 of the 6 plants get the "treated" label?

Make your guess between 1 and 40 arrangements, then reveal.

Reveal

Twenty. (63)=6×5×43×2×1=20\binom{6}{3} = \frac{6 \times 5 \times 4}{3 \times 2 \times 1} = 20. Under the null hypothesis, each of these arrangements is equally likely.

03

Count it out

Explore

An exact p-value by counting

Work through the steps, and try the last two yourself.

  1. List all 20 ways to split the six values into two groups of three.
  2. For each split, compute the treated mean minus the control mean.
  3. Try this step yourself, then reveal it
    Count the splits at least as far from zero as the observed 5. Only two reach it: the observed split, and its mirror image at −5.
  4. Try this step yourself, then reveal it
    Divide by the number of splits: p=2/20=0.10p = 2 / 20 = 0.10.

That's a complete hypothesis test: no formula, no normal curve. The only assumption is that the labels were interchangeable, which random assignment guarantees.

04

A limit you can't test past

Read

Look at that result. These are the most extreme data possible, and p is still 0.10. With 3 per group no result can reach 0.05.

More units add many more arrangements. With 6 per group there are 924. In this example 6 are as extreme as the data, so p = .006.

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.
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))))
))
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.
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)})],
})
05

Shuffle more than you can list

Explore

With 10 animals per group there are 184,756 arrangements, too many to list by hand, so this shuffler samples them at random. Try it with the lowest vitamin C dose in the tooth-growth data. Switch Statistic to the median and compare.

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?

How sure?

Data

Statistic

+30 on the last value of the second group.

Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

06

Check your reading

Checkpoint

Check yourself

With 4 treated and 4 control units, how many arrangements are there?

Show the answer

Answer: 70

(84)=70\binom{8}{4} = 70.

Check yourself

With 4 per group, what is the smallest possible two-sided p-value? Give four decimals.

Show the answer

Answer: 0.0286

Only the observed split and its mirror image can be the most extreme: 2/70≈0.02862 / 70 \approx 0.0286.

Check yourself

What does a permutation test assume when the null hypothesis is true?

Show the answer

Answer: b

No distribution is assumed. If labels weren't assigned at random, and the groups differ in other ways, then shuffling answers a weaker question.

07

Run it, and check the count

In the app

In Analyze, CodeSplash counts every split when there are at most 200,000, and otherwise samples them. These scripts check the plant example.

Python
from itertools import combinations

values = [7, 9, 11, 2, 4, 6]
observed = 5
extreme = total = 0
for treated in combinations(range(6), 3):
    a = sum(values[i] for i in treated) / 3
    b = (sum(values) - a * 3) / 3
    total += 1
    extreme += abs(a - b) >= observed - 1e-9
print(extreme, total, extreme / total)
R
values <- c(7, 9, 11, 2, 4, 6)
observed <- 5
splits <- combn(6, 3)
diffs <- apply(splits, 2, function(i) mean(values[i]) - mean(values[-i]))
extreme <- sum(abs(diffs) >= observed - 1e-9)
c(extreme, ncol(splits), extreme / ncol(splits))
08

Recap

Recap
  • If the null hypothesis is true, the labels are arbitrary, so every arrangement is equally likely.
  • A p-value is the share of arrangements at least as extreme as the one you observed.
  • The sample size limits how small a p-value can be, however strong the data look.

Concepts in this lesson