Skip to content

EProportions · Guide test 296

Hardy–Weinberg exact test

Tests genotype equilibrium with an exact conditional distribution, useful for rare genotype counts.

Runs in CodeSplashPython (calls R) example not runR example not run

Do it in CodeSplash

In the app, set it up in Analyze with this method:

In Hardy–Weinberg proportions (exact, χ², likelihood ratio), choose Test = Exact test.

Do it in CodeSplash Run this test on your own data, in Python or R.

Bench

Change the design, drag the data, move α. The statistic, its reference distribution and the verdict follow.

Bench · Hardy–Weinberg exact test

60
0.25
0.15

0 is Hardy–Weinberg equilibrium.

0.050

Alternative

Your data

Edit the counts
AAAaaa
51639

Dashed lines: the counts H₀ expects (equal shares).

If H₀ were true

n_AB = 16
  1. The reference: how n_AB varies across samples when H₀ is true, heterozygote counts given 26 minor alleles among 60 people (exact: conditional on the allele counts).
  2. Your statistic, from the data above.
  3. The p-value: the total probability of outcomes no more likely than yours (p = .121).
  4. The hatched rejection region at α = .050: statistics landing here reject H₀.

The formula

P(nAB∣nA,n)=n!  nA!  nB!  2nABnAA!  nAB!  nBB!  (2n)!,p=∑h: P(h)≤P(nAB)P(h)P(n_{AB}\mid n_A,n)=\frac{n!\;n_A!\;n_B!\;2^{n_{AB}}}{n_{AA}!\;n_{AB}!\;n_{BB}!\;(2n)!},\qquad p=\sum_{h:\,P(h)\le P(n_{AB})}P(h)

With your numbers

nAB=16 vs. expected 20.37,P(nAB)=0.07,26 minor alleles, n=60n_{AB} = 16\ \text{vs. expected } 20.37,\quad P(n_{AB}) = 0.07,\quad 26\text{ minor alleles},\ n = 60
nA, nBn_A,\ n_B
allele counts, held fixed: only how they pair into genotypes varies
P(h)P(h)
probability of each heterozygote count given the alleles (Levene–Haldane), the bars drawn

The verdict

n_AB = 16, p = .121, F = 0.21

p > α = .050: compatible with H₀

Effect size: inbreeding coefficient F = 0.214

Exact, so it stays valid with rare alleles where the χ² version fails. Genotyping error, relatedness and population structure all move it; research use, not a diagnostic.

Statistic
16.000
p-value
0.1211
Hardy–Weinberg exact test on 5, 16, 39 across 3 categories: n_AB = 16, p = .121, F = 0.21. The p-value is above α = .050, so the data are compatible with H0.

Hardy–Weinberg exact test on 5, 16, 39 across 3 categories: n_AB = 16, p = .121, F = 0.21. The p-value is above α = .050, so the data are compatible with H₀.

Question and hypotheses

H0: Hardy–Weinberg proportions conditional on the observed allele count.

Assumptions

Independent diploid individuals from a suitably defined population, reliable biallelic genotypes, and random-union-of-gametes Hardy–Weinberg proportions under H0. Relatedness, stratification and genotype error affect inference.

Formula

P(H=h∣a,N)∝2hh![(a−h)/2]![(2N−a−h)/2]!P(H=h\mid a,N)\propto\frac{2^h}{h![(a-h)/2]![(2N-a-h)/2]!}

Parameters and notation

a is count of one allele among 2N; H heterozygote count. Feasible h has matching parity and nonnegative homozygote counts; normalize over all feasible h.

Structure of the method

Condition on sample size and allele count, enumerate feasible heterozygote counts with matching parity, calculate their conditional probabilities and sum according to the declared extremeness ordering. Recursion or log-space computation avoids direct factorial overflow for larger samples.

Estimated and nuisance parameters

Conditional inference removes the unknown allele frequency from the null distribution; no concentration or regression parameters are fitted. Sample size and allele count define the conditioning set. The observed heterozygote count selects the realized table within that set.

Settings and design choices

Prespecify two-sided probability ordering, doubled one-sided tail or a heterozygote-excess/deficit alternative. The package default pvaluetype="selome" sums probabilities no larger than the observed table’s probability. Mid-p is a different less-conservative choice and is not an exact finite-sample type I error guarantee.

Fitting and adaptation

There is no neural fine-tuning. For a new marker, recompute the feasible support and conditional probabilities under the same convention. Use tolerance settings deliberately when classifying equally probable outcomes. A test across many markers requires a multiplicity procedure compatible with discrete p values.

Sensitivity and robustness

Exact calibration addresses sparse genotype counts but does not repair population mixture, relatedness or systematic genotyping errors. Different legitimate two-sided definitions can disagree, particularly for rare alleles. Report the allele count, alternative, p-value convention and any mid-p choice rather than describing all outputs simply as exact.

How to use and calibrate

Sum conditional probabilities using the specified two sided or heterozygote-deficit/excess ordering. Mid-p is an optional less-conservative variant, not an exact level guarantee.

Example application

Test equilibrium for a rare biallelic variant.

Interpretation and pitfalls

Watch out

Different exact two sided conventions can disagree; report the method and whether mid-p was used.

What changed in edition 2

  • New sections: structure of the method, estimated and nuisance parameters, settings and design choices, fitting and adaptation, sensitivity and robustness.

Python and R

Genotype counts from unrelated diploid individuals at one biallelic locus; allele frequency is estimated from these counts. Stratification, relatedness and genotyping error affect interpretation.

Python · invokes R

Not run — Python launcher syntax checked; R backend runtime not verified · needs Python standard library + Rscript; R packages: HardyWeinberg

# Python launcher for the complete R implementation below.
# Requires Rscript on PATH and the listed R packages.
import shutil
import subprocess
rscript = shutil.which("Rscript")
if rscript is None:
    raise RuntimeError("Install R and make Rscript available on PATH.")
r_code = r"""
counts<-c(AA=36,AB=48,BB=16);print(HardyWeinberg::HWExact(counts))
"""
# No shell interpolation. A failed R execution raises an error in Python.
result = subprocess.run([rscript, "--vanilla", "-"], input=r_code,
                        text=True, capture_output=True)
print(result.stdout)
if result.stderr:
    print(result.stderr)
result.check_returncode()
R

Not run — Syntax checked; runtime not verified in the final environment · needs HardyWeinberg

counts<-c(AA=36,AB=48,BB=16);print(HardyWeinberg::HWExact(counts))

Sources

Statistics guide v4 (historical):
Python: Python launcher syntax checked; R backend runtime not verified · R: Syntax checked; runtime not verified in the final environment
Reference's record:
Edition 2 review: Python: skip · R: not executed (Rscript unavailable); why not run: Python: Python-to-R bridge; Rscript is unavailable. R code was not executed. Python: Not run in the reference's review: Python-to-R bridge; Rscript is unavailable. R code was not executed. R: Reviewed but not run: R wasn't available to the reference's authors.

From the CodeSplash statistics guide (v4), entry 296, updated from the reference's edition 2 (reviewed 14 November 2026) as STAT296.