🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Permutation Tests — Distribution-Free Hypothesis Testing

Hypothesis TestingNonparametric Tests🟢 Free Lesson

Permutation Tests

Hypothesis Testing

Let the Data Generate the Null Distribution

Permutation tests create null distributions by rearranging the data itself, making no assumptions about population distributions. They provide exact p-values and work with any test statistic.

  • Non-Normal Data — Testing hypotheses when distributional assumptions are violated
  • Small Samples — Obtaining valid inference with limited observations
  • Complex Statistics — Testing custom statistics that lack standard distributional theory

Permutation tests are the ultimate fallback when standard methods fail.


What You'll Learn

  • 1State the exchangeability condition that makes label shuffling valid
  • 2Work a two-group permutation test by hand and enumerate every possible allocation
  • 3Choose between exact enumeration and Monte Carlo sampling, including the plus-one p-value
  • 4Apply permutation logic to statistics that have no textbook reference distribution

A permutation test answers one question with a strategy that looks almost too simple: instead of comparing your statistic to a reference curve borrowed from a table, it builds that reference curve out of your own observations. Under the null hypothesis the group labels carry no information, so every reassignment of labels that preserves the group sizes is equally plausible. Compute the statistic for each reassignment, then count the fraction that land at least as far from zero as the one you actually observed. That fraction is the p-value. Nothing about the shape of the population, the equality of variances, or the value of the standard deviation enters the calculation.

The freedom is real but it is not free. You are trading a distributional assumption for a design assumption, and if that design assumption is wrong the p-value is wrong too. The next section spells out exactly what has to be true, because "no assumptions" is the most common misreading of the method.

Why Shuffling Labels Is a Valid Test

Randomisation inference rests on exchangeability: under the sharp null hypothesis of no effect, the joint distribution of the observations is unchanged by reassigning the labels. In a randomised experiment this is guaranteed by the design itself. The coin flip that sent each subject to an arm means that, before outcomes were revealed, every allocation with the same arm sizes was equally likely, so shuffling the labels you observed reproduces the assignment mechanism the experiment actually used.

In an observational study the guarantee is weaker. If treatment assignment depended on hospital site, then swapping a treated patient at site A with an untreated patient at site B breaks the assignment mechanism, and the resulting null distribution is not the right one. The fix is to shuffle within blocks — permute labels only among patients who shared the same site, cohort, or matched set. The same idea extends to regression: when you want to test whether predictor adds information beyond covariates , you permute the residuals from the reduced model rather than the raw response, a scheme published by Freedman and Lane in 1983.

The plus-one in the numerator is deliberate. If you never see a permuted statistic as extreme as the observed one, the naive fraction is zero, and a p-value of exactly zero claims an impossibility that no finite sample can establish. Adding one permutation — the observed labelling itself — guarantees a strictly positive, valid p-value.

The Permutation Algorithm, Step by Step

  1. Choose a test statistic that measures the effect you care about: difference in means, difference in medians, a correlation, a slope, or anything else.
  2. Compute on the data exactly as labelled.
  3. Shuffle the labels across observations while preserving the original group sizes, or draw a random assignment from the set of allowed assignments.
  4. Recompute on the shuffled data and store it.
  5. Repeat steps 3 and 4 times, or enumerate every allowed assignment when the count is small.
  6. Compare to the resulting collection: the two-sided p-value is the share of permuted values at least as extreme in absolute value.

Two details decide whether the result is trustworthy. First, the same statistic must be used in every iteration; recomputing a slightly different quantity each round silently mixes different null distributions. Second, ties must be handled consistently — using greater-than-or-equal when counting, never strict greater-than, or the test becomes anti-conservative when the statistic is discrete.

A Worked Example You Can Check by Hand

Take three control measurements 2.1, 2.5, 3.0 and three treated measurements 4.2, 4.8, 5.1. The statistic is the difference in means.

There are only ways to split six observations into two groups of three, so every one of them can be enumerated. Because the pooled total is 21.7, the difference for any split depends only on the sum of the three values placed in group A:

Requiring forces either or . Only two of the twenty splits satisfy that: the original labelling, with sum 7.6, and its mirror image, with sum 14.1. The exact two-sided p-value is therefore

With three observations per group the smallest p-value any exact permutation test can produce is 2/20, so no amount of observed separation can reach the conventional 0.05 threshold. Power in a permutation test is still governed by sample size; the method removes the normality assumption, not the laws of evidence.

Exact Enumeration Versus Monte Carlo Sampling

When the number of allowed assignments is modest, you can enumerate them all and obtain a p-value that is exact up to arithmetic. When it explodes, you sample. The count for a two-group comparison depends only on group sizes:

Group sizesTotal arrangementsPractical verdict
2 and 26Enumerate
3 and 320Enumerate
5 and 5252Enumerate
10 and 10184,756Enumerate in under a second
15 and 15155,117,520Enumerate only with care
20 and 20137,846,528,820Sample instead

Monte Carlo sampling introduces its own error, and that error is quantifiable. The estimated p-value is a binomial proportion based on draws, so its standard error is . At with permutations the standard error is about 0.0022, which is small enough for ordinary decisions. To resolve a p-value near 0.05 to within plus or minus 0.005 you need roughly permutations; run 10,000 and the resolution is comfortable. Report alongside every Monte Carlo p-value so a reader can judge that resolution.

Python Implementation

python
# Visualize permutation distribution
fig, ax = plt.subplots(figsize=(10, 5))
ax.hist(perm_diffs, bins=50, density=True, color='lightblue', edgecolor='black', alpha=0.7)
ax.axvline(observed_diff, color='red', linewidth=2, linestyle='--',
           label=f'Observed = {observed_diff:.3f}')
ax.axvline(-observed_diff, color='red', linewidth=2, linestyle='--')
ax.fill_betweenx([0, 0.15], -20, -abs(observed_diff), alpha=0.3, color='red', label=f'p = {p_perm:.4f}')
ax.fill_betweenx([0, 0.15], abs(observed_diff), 20, alpha=0.3, color='red')
ax.set_title(f'Permutation Distribution of Difference in Means\n(n_perm={n_permutations:,})')
ax.set_xlabel('Difference in Means (A - B)')
ax.legend()
plt.tight_layout()
plt.savefig('permutation_test.png', dpi=150)
plt.show()

The histogram above is the null distribution: centred on zero because every random relabelling splits the pooled observations into two groups sharing one overall mean, and spread entirely by your own data.

Choosing Which Statistic to Permute

The difference in means is the default, not the only option. Permute the difference in medians when a handful of extreme values dominate the mean, permute a trimmed mean when you want robustness with power, or permute a ratio when the research question is multiplicative. Because the permutation machinery is agnostic, the choice of statistic becomes a scientific decision rather than a constraint imposed by a reference distribution.

Correlation is the second most common use. The null hypothesis of zero linear association is tested by holding fixed and scrambling , which destroys any pairing while preserving both marginal distributions:

python
# Permutation test for correlation (also distribution-free)
x = np.random.normal(0, 1, 30)
y = 0.5 * x + np.random.normal(0, 1, 30)

obs_r, _ = stats.pearsonr(x, y)
perm_r = [stats.pearsonr(np.random.permutation(x), y)[0] for _ in range(10000)]
p_corr_perm = (np.abs(perm_r) >= np.abs(obs_r)).mean()

print(f"\nCorrelation: r = {obs_r:.4f}")
print(f"Permutation p-value: {p_corr_perm:.4f}")

The same pattern generalises to model comparison: permute the rows of a design matrix, refit, and record the change in or in mean squared error. Any statistic you can compute, you can test.

Permutation, Bootstrap, and Parametric Tests Compared

AspectParametric testPermutation testBootstrap
What it assumesDistributional form, often normalityExchangeability under the nullObservations are representative
What it producesp-value against a tablep-value against a shuffled nullConfidence interval for an estimator
Null built fromTheoryYour own data, relabelledYour own data, resampled
Any statisticOnly those with closed formsAny statistic at allAny statistic at all
Typical costNegligibleThousands of refitsThousands of refits
Small samplesUnreliable if normality failsExact when enumeratingUnstable below roughly 30

The distinction between permutation and bootstrap deserves emphasis because the two are frequently conflated. Permuting mixes observations across groups to simulate a world in which the null hypothesis is true. Bootstrapping resamples within groups to simulate repeated sampling from the world you observed. One answers "is there an effect", the other answers "how precise is my estimate".

Common Mistakes

Shuffling individual cell values instead of the labels that define the groups

Fix: Permute at the level of randomisation. If subjects were assigned, shuffle subject labels; if whole clusters were assigned, shuffle clusters.

Reporting a Monte Carlo p-value of 0.0000

Fix: Use the plus-one correction, (extreme + 1) / (B + 1), and always report B so the reader can see the resolution.

Assuming permutation tests are assumption free

Fix: They replace the distributional assumption with exchangeability. In observational or clustered data, permute within blocks or use a residual scheme.

Best Practices

  • Fix the random seed before comparing permutation results across runs
  • Report the statistic, B, the observed value, and the Monte Carlo standard error together
  • Cross-check a small dataset by full enumeration to validate your permutation code

Key Takeaways

  • The p-value is the share of allowed relabelings whose statistic is at least as extreme as the observed one
  • With 3 versus 3 observations only 20 allocations exist, so the smallest attainable exact p-value is 0.10
  • Monte Carlo resolution is sqrt(p(1-p)/B); 10,000 permutations give a standard error near 0.002 at p = 0.05
  • Permutation tests replace distributional assumptions with exchangeability, so block or residual permutation matters outside experiments

Frequently Asked Questions

Is a permutation test the same as a bootstrap?

No. Permutation resamples across groups to construct the distribution expected when the null is true, and it returns a p-value. Bootstrap resamples within groups to construct the sampling distribution of an estimator, and it returns a confidence interval. They answer different questions even though both rely on repeated resampling.

Do I still need a large sample for a permutation test?

You need enough observations for the statistic to have resolution. A two-versus-two design offers only six allocations and can never produce a p-value below 0.167 regardless of effect size. Permutation removes the normality assumption; it does not create information that the design never contained.

When should I prefer the t-test over a permutation test?

When samples are moderate to large, the data are reasonably symmetric, and variance is comparable across groups, the t-test is marginally more powerful and costs nothing to compute. Reach for permutation testing when samples are small, distributions are skewed or heavy tailed, variances differ sharply, or the statistic you want to test has no textbook reference distribution at all.

Interview Questions

Q1: Why does shuffling labels produce a valid null distribution?

Under the sharp null the labels carry no information, so every assignment with the same group sizes is equally likely. Evaluating the statistic on each assignment reproduces the distribution the statistic would have if the null were true.

Q2: How many permutations do you need?

Enough that the Monte Carlo standard error is small relative to your decision threshold. Near p = 0.05, 10,000 permutations give a standard error around 0.002; 1,900 is roughly the minimum for a plus or minus 0.005 resolution.

Q3: Can a permutation test ever return a p-value of exactly zero?

Not with the plus-one correction. The observed labelling is always counted among the B plus one assignments, so the p-value is bounded below by 1/(B+1).

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Statistics Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement