HomeAll CategoriesFisher's Exact Test Calculator: Free 2x2 P-Value & Steps

Fisher’s Exact Test Calculator: Free 2×2 P-Value & Steps

Fisher's Exact Test Calculator

Get the exact two-sided and one-sided p-value for any 2×2 contingency table, with the odds ratio and its Woolf or exact confidence interval (the same as R's fisher.test), mid-p, relative risk, phi, four charts and an APA write-up. Built for small samples where chi-square fails.

Non-Parametric2×2 TableExact P-ValueOdds Ratio + CISmall SamplesAPA 7

⚡ 0. Quick Answer

Fisher's exact test checks whether two yes/no variables are linked in a 2×2 table.

It adds up exact hypergeometric probabilities of every table that is as unlikely as yours, so it stays valid when chi-square fails (any expected count below 5). For 12/15 cured on treatment vs 3/15 on placebo, two-sided p = 0.0028 and the odds ratio is 16.0.

P(a) = C(a+b, a) × C(c+d, c) ÷ C(n, a+c)

Rule of thumb: p below 0.05 means the proportions differ. Report the odds ratio with its 95% CI, and switch to McNemar's test if the same subjects were measured twice.

Key takeaways

  • Use this Fisher's exact test calculator for a 2×2 table of counts when any expected count is below 5 or n is under about 40.
  • The two-sided p-value adds every table with probability ≤ the observed one; R, SciPy and SPSS use the same rule.
  • Worked check: 12/15 vs 3/15 cured gives p = 0.0028, sample OR = 16.00, Woolf 95% CI 2.67 to 95.75.
  • R reports the conditional MLE odds ratio (14.12 here), not ad/bc; pick Exact conditional to match it.
  • You need at least 4 per group before even a perfect split (4/4 vs 0/4) can reach p < 0.05 (p = 0.0286).

📚 1. What Is Fisher's Exact Test?

Fisher's exact test is a significance test for a 2×2 contingency table. It asks one question: is the proportion with the outcome the same in both groups? It answers by computing the exact probability of your table, and of every more extreme table, when the row and column totals are held fixed.

R. A. Fisher described it in 1922 and made it famous in 1935 with the lady tasting tea experiment. A colleague claimed she could tell whether milk or tea went into the cup first. With 3 of 4 cups right, Fisher showed p = 0.486, which is no evidence at all. J. O. Irwin found the same test in 1935, so it is also called the Fisher-Irwin test.

What it measures: the strength of evidence against independence. The p-value is the evidence; the odds ratio is the size and direction of the link.

A worked one-liner: with cells 12, 3, 3, 12 the observed table has probability 455 × 455 ÷ 155,117,520 = 0.001335. Adding the 8 tables that are this unlikely or less gives p = 0.0028.

Hypergeometric probabilities of cell a from 0 to 15 with all margins equal to 15. Observed a = 12 has probability 0.0013; the counted tails add to p = 0.0028.0123456789101112131415Value of cell a (Treatment cured), all margins fixed at 15■ observed a = 12■ as or less likely: counted■ more likely: not counted
The 16 possible tables for the drug trial. The burnt orange bar is the observed table; the amber tails are counted into the two-sided p-value.

Who uses it: clinical researchers for small trials and rare side effects, epidemiologists for outbreak tables, ecologists for detection and presence data, geneticists for allele counts, and marketers for small A/B tests.

Fisher's exact testChi-square test
p-valueExact, from the hypergeometric distributionApproximate, from the chi-square curve
Sample sizeAny n, best for small or sparse tablesNeeds every expected count of 5 or more
Table size2×2 (r×c with Freeman-Halton)Any r×c
BehaviourOften conservativeCan be too liberal in small samples
Drug trial examplep = 0.0028p = 0.0010 (no correction)

🧮 2. Set Up Your Data

Dataset 1 is loaded for you. Nothing is computed until you press Run.

Enter 0/1 outcomes for each group, separated by commas (1 = event, 0 = no event). Group names are editable.

Comma-separated. Each value must be 0 or 1.
Comma-separated. Each value must be 0 or 1.
Two numeric columns of 0/1 values, one per group. Headers are detected automatically.

Type the counts and edit the group and outcome names. Use the buttons to grow the table up to 8 × 8. A 2×2 table runs Fisher's exact test; anything larger runs the Fisher-Freeman-Halton exact test.

Table size: 2 × 2.


📊 3. Results

Enter or load your data above, then press Run Fisher's Exact Test. The 2×2 table, exact p-values, odds ratio with CI, assumption checks, four charts and the export buttons will appear here.

🧠 4. Interpretation of Results, In Detail

Run the test to fill this box with your own numbers: what was found, what the p-value means, the effect size, practical importance and next steps. Results so far: p = ___, OR = ___, 95% CI ___.

4.6 What the p-value does and does not say

The p-value is the chance of a table at least as lopsided as yours if group and outcome were unrelated. A p of 0.0028 means about 3 in 1,000. It is not the chance that the null hypothesis is true, and it is not the size of the effect.

4.7 Reading the odds ratio, and why R shows a different number

The sample odds ratio is ad/bc. For 12, 3, 3, 12 that is 16.00. R's fisher.test reports the conditional maximum likelihood estimate, 14.12, which fits the hypergeometric model exactly. Both are correct. Say which one you report, and pair it with the matching interval.

4.8 Why the p-value and the exact CI can disagree

The usual two-sided p-value sums every table no more likely than yours. The usual exact CI inverts two one-sided tests at α/2 each. These are different rules, so near 0.05 they can disagree, as in Example 3 (p = 0.041, CI 0.90 to 93.44). Fay (2010) describes this and offers matching intervals. Report both numbers and the method.

4.9 One-tailed or two-tailed?

Use two-tailed unless you wrote down a direction before seeing data. The one-tailed p is roughly half the two-tailed p, so choosing it after the fact doubles your false-positive risk.

4.10 Mid-p and conservatism

Because the hypergeometric distribution is discrete, Fisher's real false-positive rate is often well below 5%. The mid-p value subtracts half of the observed table's probability. Lydersen and colleagues (2009) found mid-p behaves close to the best unconditional tests, so it is a fair sensitivity check.

4.11 Odds ratio or relative risk?

Relative risk compares proportions directly (80% vs 20% gives RR = 4.0). The odds ratio is larger when the outcome is common (16.0 here). In a case-control study only the odds ratio is valid. In a trial, readers find RR and the risk difference easier to grasp, so report them alongside.

4.12 Decision guide

You seeIt meansDo this
p below α and CI excludes 1Clear associationReport p, OR and CI; describe the direction
p below α but exact CI touches 1Borderline evidenceReport both, note the test and CI rules differ
p above α, narrow CI around 1Little or no effectReport the CI as evidence of a small effect
p above α, wide CIUnderpowered studyDo not claim no effect; plan a larger sample
Large n, tiny phiSignificant but trivialJudge practical importance with RD and RR

4.13 Common mistakes this calculator prevents

  • Using chi-square when expected counts are below 5: the assumption check flags it.
  • Crashing on a zero cell: the Woolf CI adds 0.5 and the exact CI needs no correction.
  • Reporting only p: the odds ratio, RR, RD and phi are always shown.
  • Confusing ad/bc with R's estimate: both are listed and labelled.

✍ 5. How to Write Your Results in Research

▶ Run the analysis above to auto-fill all five examples: APA 7th, thesis, plain-language, structured abstract and pre-registration.

Example 1, APA 7th Edition
A Fisher's exact test examined the association between group and outcome, p = ___, OR = ___, 95% CI [___, ___], φ = ___.

∑ 6. Formulas Used

①
Probability of the Observed Table (Hypergeometric)
P(a) = C(a+b, a) × C(c+d, c) ÷ C(n, a+c)
a, b, c, dThe four cell counts, whole numbers
nGrand total, a + b + c + d
C(n, k)Binomial coefficient, n! ÷ (k!(n − k)!), unitless
RequiresRow and column totals held fixed
r×c tablesP = (∏Ri! ∏Cj!) ÷ (n! ∏nij!), the Freeman-Halton extension
ExampleC(15,12) × C(15,3) ÷ C(30,15) = 0.001335
②
Two-Sided Exact P-Value
p = Σ P(a*) for every a* with P(a*) ≤ P(aobs)
a*Every possible value of cell a with the same margins
Range of a*max(0, a+c − (c+d)) to min(a+b, a+c)
ToleranceTies counted with a relative tolerance of 1 + 10⁻⁷, as in R
ExampleSum over a* = 0 to 3 and 12 to 15 gives 0.0028
③
One-Sided P-Values and Mid-p
pright = Σ P(a* ≥ a)  ·  pleft = Σ P(a* ≤ a)  ·  mid-p = p − ½P(a)
prightTests OR above 1, group 1 has higher odds
pleftTests OR below 1
mid-pLess conservative version; unitless
Examplepright = 0.0014, mid-p = 0.0021
④
Odds Ratio and Woolf Confidence Interval
OR = ad ÷ bc  ·  SE = √(1/a + 1/b + 1/c + 1/d)  ·  CI = exp(ln OR ± z × SE)
OROdds ratio, unitless, 1 means no association
SEStandard error of ln OR
z1.96 for 95%, 2.576 for 99%
Zero cellAdd 0.5 to every cell first (Haldane-Anscombe)
ExampleOR = 16.00, SE = 0.913, CI 2.67 to 95.75
⑤
Exact Conditional Odds Ratio and CI
Pψ(x) ∝ C(a+b, x) C(c+d, a+c−x) ψx  ·  PψL(X ≥ a) = α/2, PψU(X ≤ a) = α/2
ψTrue odds ratio in the noncentral hypergeometric model
ψL, ψULower and upper exact limits
Conditional MLEThe ψ whose expected value of X equals a; what R prints
ExampleMLE 14.12, exact CI 2.11 to 139.37
⑥
Effect Sizes for a 2×2 Table
φ = (ad − bc) ÷ √[(a+b)(c+d)(a+c)(b+d)]  ·  RR = [a/(a+b)] ÷ [c/(c+d)]  ·  RD = a/(a+b) − c/(c+d)
φPhi, from −1 to 1; bands 0.10, 0.30, 0.50
RRRelative risk, unitless
RDRisk difference, a proportion
Exampleφ = 0.60, RR = 4.00, RD = 0.60
⑦
Expected Counts and the Assumption Check
Eij = (row totali × column totalj) ÷ n
EijCount expected in a cell if the variables were unrelated
RuleAny E below 5: chi-square unreliable, Fisher preferred
ExampleEvery E = 15 × 15 ÷ 30 = 7.5 in the drug trial

🔀 7. Fisher's Exact Test Calculation Flowchart, Step by Step

This flowchart shows how Fisher's exact test is calculated, step by step, from raw counts to a reportable result. Every box uses the drug trial example: 12 of 15 cured on treatment and 3 of 15 on placebo.

Start or resultData stepCalculation stepYes or no check
StartRaw outcomes30 patients, two groups of 15, each cured or not
1
Build the 2×2 tablea, b, c, da = 12, b = 3, c = 3, d = 12
CheckIs any expected count below 5?
YesChi-square is unreliable. Fisher is the right test.
NoEvery expected count is 7.5. Chi-square would also work, Fisher is still exact.
2
Find the marginsa+b, c+d, a+c, b+d, nRows 15, 15; columns 15, 15; n = 30
3
Probability of the observed tableC(15,12) × C(15,3) ÷ C(30,15)455 × 455 ÷ 155,117,520 = 0.001335
4
List every possible tablea* from 0 to 1516 tables share these margins
5
Add the tables no more likely than yoursΣ P(a*) ≤ 0.001335a* = 0 to 3 and 12 to 15, so p = 0.0028
CheckWere the same subjects measured twice (paired data)?
Yes, stopFisher does not apply. Use McNemar's test.
NoTwo independent groups, so Fisher applies.
6
Odds ratio and its CIOR = ad ÷ bc144 ÷ 9 = 16.00, Woolf 95% CI 2.67 to 95.75
CheckIs p below α = 0.05?
YesEvidence of an association. Report the direction.
NoNot enough evidence. Report the CI, do not claim no effect.
Resultp = 0.0028, OR = 16.00 [2.67, 95.75], φ = 0.60Significant Large effectRule used: p below 0.05 and CI excludes 1.

Check any box yourself: the Excel sheet in Section 9, the R script in Section 10 and the Python script in Section 11 all return p = 0.0028 for this table.

📝 8. How to Use This Calculator

  1. Pick a sample or enter your data. Choose one of the 10 sample datasets, or paste 0/1 outcomes for each group.
  2. Name the groups and outcomes. Type your own group and outcome labels. They appear in every table, chart and write-up.
  3. Or upload a file. On the Upload tab choose a CSV or Excel file and click the two columns that hold the 0/1 outcomes.
  4. Or type the counts. On the Manual Table tab type the counts. Use Add row and Add column for tables up to 8x8, which run the Fisher-Freeman-Halton exact test.
  5. Set alpha. 0.05 is standard. 0.01 or 0.10 change the confidence level to 99% or 90%.
  6. Pick the tail. Two-tailed unless you wrote down a direction before collecting data.
  7. Pick the CI method. Woolf for the simple ad/bc odds ratio, or Exact conditional to match R's fisher.test.
  8. Run the test. Press Run Fisher's Exact Test. Nothing is computed until you do.
  9. Read the results. Check the p-value, odds ratio and CI cards, the full table, the assumption checks and the four charts.
  10. Report and export. Copy one of five write-ups from Section 5, or download a TXT report or a print-ready PDF.

📈 9. How to Run Fisher's Exact Test in Excel

Excel has no Fisher button, but its HYPGEOM.DIST function gives the probability of each table, and two more formulas turn those into the exact p-value. This section rebuilds the drug trial result, p = 0.0028, with the spreadsheet shown at every step.

The whole thing in one line: list a* = 0 to 15 in A2:A17, put =HYPGEOM.DIST(A2,15,15,30,FALSE) in B2 and fill down, then sum the cells no larger than the observed one.

9.1 The functions you need

You wantExcel functionNote
Probability of one table=HYPGEOM.DIST(a, row1, col1, n, FALSE)FALSE gives the single probability, not the running total
Right-tail p (OR above 1)=1-HYPGEOM.DIST(a-1, row1, col1, n, TRUE)TRUE gives the cumulative total up to a-1
Left-tail p (OR below 1)=HYPGEOM.DIST(a, row1, col1, n, TRUE)Cumulative up to and including a
Two-sided p=SUMIF(B2:B17,"<="&B14*(1+1E-7))Adds every probability no larger than the observed one
Sample odds ratio=(B2*C3)/(C2*B3)ad ÷ bc from the table sheet
z for a 95% CI=NORM.S.INV(0.975)1.959964
Chi-square p, for comparison=CHISQ.TEST(actual, expected)Needs a second table of expected counts

9.2 Step by step

1 Type the 2×2 table

Put group names in column A and the two outcome counts in B and C. Add a total row so the margins are on screen.

=SUM(B2:B3)
Xfisher.xlsx - ExcelB4fx=SUM(B2:B3)ABC1GroupCuredNot cured2Treatment1233Placebo3124Total1515

Cells B2:C3 hold a = 12, b = 3, c = 3, d = 12. The column 1 total in B4 is 15.

2 List every possible table and its probability

On a new sheet, type a* = 0 to 15 down A2:A17. B gives each probability; C keeps it only if it is as small as the observed one (row 14 holds a* = 12).

=HYPGEOM.DIST(A2,15,15,30,FALSE)=IF(B2<=$B$14*(1+1E-7),B2,0)
Xfisher.xlsx - ExcelB2fx=HYPGEOM.DIST(A2,15,15,30,FALSE)ABC1a*P(a*)Counted206.45E-096.45E-09311.45E-061.45E-06420.0000710.000071530.0013350.001335640.0120120750.0581370860.1614910970.2669540

Rows 2 to 5 (a* = 0 to 3) are counted; rows 6 to 9 are more likely than the observed table, so C shows 0. Only the first eight values are shown.

3 Add up the counted probabilities

The sum of column C is the two-sided exact p-value. The one-sided values come straight from the cumulative form.

=SUM(C2:C17)=1-HYPGEOM.DIST(11,15,15,30,TRUE)=HYPGEOM.DIST(12,15,15,30,TRUE)
Xfisher.xlsx - ExcelF3fx=SUM(C2:C17)EF1StatisticValue2P(observed)0.0013353Two-sided p0.0028144Right-tail p0.0014075Left-tail p0.999927

Two-sided p = 0.002814 in F3, matching R and SciPy. The right-tail p is 0.001407.

4 Add the odds ratio and its Woolf CI

The odds ratio uses the table sheet; the CI is built on the log scale.

=(Table!B2*Table!C3)/(Table!C2*Table!B3)=SQRT(1/Table!B2+1/Table!C2+1/Table!B3+1/Table!C3)=EXP(LN(F6)-NORM.S.INV(0.975)*F7)
Xfisher.xlsx - ExcelF8fx=EXP(LN(F6)-NORM.S.INV(0.975)*F7)EF1StatisticValue2P(observed)0.0013353Two-sided p0.0028144Right-tail p0.0014075Left-tail p0.9999276Odds ratio16.00007SE of ln OR0.91298CI lower2.67359CI upper95.7540

OR = 16.0000 with 95% CI 2.6735 to 95.7540, the same as the calculator's Woolf setting.

Argument order matters. HYPGEOM.DIST takes (successes in sample, sample size, successes in population, population size). Use (a, row 1 total, column 1 total, n). With equal margins any order works, which hides the mistake until your margins differ. The old HYPGEOMDIST function has no cumulative argument and cannot give one-sided p-values.

9.3 The awkward cases

  • A zero cell. The p-value still works. The odds ratio formula divides by zero, so add 0.5 to every cell before the OR and SE formulas.
  • Unequal margins. The range of a* runs from MAX(0, col1 − row2) to MIN(row1, col1). List only those values.
  • Large tables. With n in the thousands HYPGEOM.DIST still works but returns tiny numbers; format column B as Scientific so they do not display as 0.

9.4 Why your Excel answer might differ from R, Python or SPSS

SituationWhat happensFix
Odds ratio is 14.12 in R but 16 hereR prints the conditional MLE; Excel and SciPy use ad/bcBoth are right. Name the one you report
CI differs from RR uses the exact conditional CI, this sheet uses WoolfChoose Exact conditional in the calculator to match R
Two-sided p is double the one-sided p in a textbookSome books double the smaller tail instead of summing small tablesR, SciPy and SPSS sum tables with P ≤ P(observed); so does this page
p slightly different in the 6th decimalTie tolerance when two tables have equal probabilityUse the 1 + 1E-7 tolerance shown in step 2
Chi-square p is much smallerChi-square is an approximation that fails with small expected countsReport Fisher when any expected count is below 5

9.5 Charting the result in Excel

  1. Select the group names and the two outcome counts.
  2. Insert → Charts → 100% Stacked Bar.
  3. Add data labels showing the percentage in each segment.
  4. Put the Fisher p-value and odds ratio in the chart title or caption.

9.6 Excel errors you will probably hit

Excel showsWhyFix
#NUM!a* is larger than the row or column totalList only valid a* values (see 9.3)
#DIV/0! in the ORA zero cellAdd 0.5 to every cell for the OR and SE
P(a*) shows 0The number is smaller than the cell format showsFormat as Scientific with 2 decimals
#NAME?Very old Excel without HYPGEOM.DISTUse HYPGEOMDIST (two-sided only) or upgrade
Sum of all P(a*) is not 1Missing or extra rows in A2:A17Check the a* range runs over every valid value

📈 10. How to Run Fisher's Exact Test in R

R has Fisher's exact test built in as fisher.test(). The script below is complete and runnable: it prints the two-sided and one-sided p-values, mid-p, both odds ratios with their intervals, phi and a plain-English verdict, and saves one 300 dpi figure. It uses base R only.

Copy the whole block. It runs top to bottom in RStudio or with Rscript fisher.R. Change only the matrix(c(12, 3, 3, 12) ...) line, or switch to the CSV option.

10.1 The complete script

R, base only, saves fisher_plot.png

# ============================================================
# Fisher's exact test for a 2x2 table, with one publication figure
# StatsUnlock - https://statsunlock.com/fishers-exact-test-calculator/
# Base R only. No packages to install.
# ============================================================

# ---- 1. Your data ------------------------------------------
# Option A: type the four counts (rows = groups, cols = outcome)
tab <- matrix(c(12, 3,
                3, 12), nrow = 2, byrow = TRUE,
              dimnames = list(Group   = c("Treatment", "Placebo"),
                              Outcome = c("Cured", "Not cured")))
# Option B: build it from a CSV with one row per subject
#   df  <- read.csv("data.csv")
#   df  <- df[!is.na(df$group) & !is.na(df$outcome), ]   # drop missing
#   tab <- table(df$group, df$outcome)
alpha <- 0.05
print(tab)

# ---- 2. The exact test -------------------------------------
ft       <- fisher.test(tab)                           # two-sided
ft_right <- fisher.test(tab, alternative = "greater")  # OR above 1
a <- tab[1, 1]; b <- tab[1, 2]; c <- tab[2, 1]; d <- tab[2, 2]
n <- sum(tab); r1 <- a + b; c1 <- a + c

# ---- 3. Mid-p, sample OR with Woolf CI, effect sizes --------
p_obs <- dhyper(a, r1, n - r1, c1)      # probability of this table
mid_p <- ft$p.value - 0.5 * p_obs
k <- if (any(tab == 0)) 0.5 else 0       # Haldane-Anscombe if a zero
or_s  <- ((a + k) * (d + k)) / ((b + k) * (c + k))
se    <- sqrt(1/(a+k) + 1/(b+k) + 1/(c+k) + 1/(d+k))
woolf <- exp(log(or_s) + c(-1, 1) * qnorm(1 - alpha/2) * se)
phi   <- (a*d - b*c) / sqrt(r1 * (c + d) * c1 * (b + d))
expected <- outer(rowSums(tab), colSums(tab)) / n

cat(sprintf("\nTwo-sided exact p   = %.4f\n", ft$p.value))
cat(sprintf("Right-tailed p      = %.4f\n", ft_right$p.value))
cat(sprintf("Mid-p (two-sided)   = %.4f\n", mid_p))
cat(sprintf("Sample OR (ad/bc)   = %.2f, Woolf 95%% CI %.2f to %.2f\n", or_s, woolf[1], woolf[2]))
cat(sprintf("Conditional MLE OR  = %.2f, exact 95%% CI %.2f to %.2f\n",
            ft$estimate, ft$conf.int[1], ft$conf.int[2]))
cat(sprintf("Phi                 = %.2f\n", phi))
cat(sprintf("Smallest expected count = %.2f\n", min(expected)))

verdict <- if (ft$p.value < alpha) "evidence of an association" else "no clear evidence of an association"
cat(sprintf("\nVerdict: p = %.4f, so there is %s between group and outcome.\n",
            ft$p.value, verdict))

# ---- 4. One 300 dpi figure ---------------------------------
png("fisher_plot.png", width = 2700, height = 1200, res = 300)
par(mfrow = c(1, 2), mar = c(4.6, 6.5, 3, 1))
props <- prop.table(tab, 1) * 100
barplot(t(props), horiz = TRUE, las = 1, col = c("#16a34a", "#f59e0b"),
        border = NA, xlab = "Percent of group", main = "Outcome by group",
        legend.text = colnames(tab),
        args.legend = list(x = "bottomright", bty = "n", cex = 0.75))

par(mar = c(4.6, 4.6, 3, 1))
xs   <- max(0, c1 - (n - r1)):min(r1, c1)
px   <- dhyper(xs, r1, n - r1, c1)
cols <- ifelse(xs == a, "#c2410c",
        ifelse(px <= p_obs * (1 + 1e-7), "#f59e0b", "#93c5fd"))
barplot(px, names.arg = xs, col = cols, border = NA,
        xlab = "Value of cell a", ylab = "Probability",
        main = sprintf("Exact two-sided p = %.4f", ft$p.value))
dev.off()
cat("\nSaved fisher_plot.png\n")

10.2 What each part does

Line or functionWhat it does, and why it is there
matrix(..., byrow = TRUE)Builds the 2×2 table row by row: Treatment 12, 3 then Placebo 3, 12. dimnames labels rows and columns so the output is readable.
table(df$group, df$outcome)The CSV route: counts subjects in each group and outcome combination.
fisher.test(tab)Two-sided exact p-value, the conditional MLE odds ratio and its exact 95% CI.
alternative = "greater"One-sided test that the odds ratio is above 1.
dhyper(a, r1, n - r1, c1)Hypergeometric probability of the observed table, used for mid-p and the figure.
k <- 0.5 if a zeroHaldane-Anscombe correction so the Woolf OR and SE stay finite.
qnorm(1 - alpha/2)1.96 for a 95% interval.
outer(rowSums, colSums) / nExpected counts, the basis of the chi-square rule of thumb.
png(..., res = 300)Opens a print-quality file. Without res the image is a blurry 72 dpi.
dev.off()Closes and writes the file. Forgetting it leaves an empty PNG.

10.3 What the figure shows

The left panel shows the percentage with each outcome in each group, so the size of the difference is obvious. The right panel shows every table that shares your margins: the burnt orange bar is your table and the amber bars are the tails added into the p-value.

10.4 Common R problems and fixes

SymptomCauseFix
Odds ratio is not ad/bcfisher.test reports the conditional MLEUse the or_s line for ad/bc
Error: 'x' must have at least 2 rows and columnsA group or outcome has no subjectsCheck the table; a whole row or column of zeros cannot be tested
Rows in the wrong ordertable() sorts labels alphabeticallyUse factor(df$group, levels = c("Treatment", "Placebo"))
FEXACT error on a big r×c tableWorkspace too smallAdd workspace = 2e8, or simulate.p.value = TRUE
The PNG is emptydev.off() not reachedRun the whole script, or call dev.off() by hand

10.5 Useful one-liners

You wantR code
Two-sided p onlyfisher.test(tab)$p.value
One-sided, OR below 1fisher.test(tab, alternative = "less")
99% exact CIfisher.test(tab, conf.level = 0.99)$conf.int
Chi-square for comparisonchisq.test(tab, correct = FALSE)
Expected countschisq.test(tab)$expected
r×c Freeman-Haltonfisher.test(bigtab)

📈 11. How to Run Fisher's Exact Test in Python

SciPy gives Fisher's exact test as scipy.stats.fisher_exact and the R-style conditional odds ratio as scipy.stats.contingency.odds_ratio. The script below prints every statistic on this page, a plain-English verdict, and saves one 300 dpi figure.

Copy the whole block. Change only the table = np.array(...) line, or use the CSV option.
numpythe table and the arithmetic
scipyfisher_exact, hypergeom, odds_ratio
matplotlibthe figure

Install with pip install numpy scipy matplotlib. odds_ratio needs SciPy 1.10 or later.

11.1 The complete script

Python 3, saves fisher_plot.png

# ============================================================
# Fisher's exact test for a 2x2 table, with one publication figure
# StatsUnlock - https://statsunlock.com/fishers-exact-test-calculator/
# ============================================================
import numpy as np
import matplotlib
matplotlib.use("Agg")                 # save to file, no window needed
import matplotlib.pyplot as plt
from scipy.stats import fisher_exact, hypergeom, norm
from scipy.stats.contingency import odds_ratio, expected_freq

# ---- 1. Your data ------------------------------------------
# rows = groups, columns = outcome (event, no event)
table = np.array([[12, 3],
                  [3, 12]])
groups   = ["Treatment", "Placebo"]
outcomes = ["Cured", "Not cured"]
# Or build it from a CSV with one row per subject:
#   import pandas as pd
#   df = pd.read_csv("data.csv").dropna(subset=["group", "outcome"])
#   table = pd.crosstab(df["group"], df["outcome"]).to_numpy()
alpha = 0.05

# ---- 2. The exact test -------------------------------------
res       = fisher_exact(table)                          # two-sided
res_right = fisher_exact(table, alternative="greater")   # OR above 1
(a, b), (c, d) = table
n, r1, c1 = table.sum(), a + b, a + c

# ---- 3. Mid-p, odds ratios, effect sizes -------------------
rv    = hypergeom(n, r1, c1)          # population, row-1 total, column-1 total
p_obs = rv.pmf(a)
mid_p = res.pvalue - 0.5 * p_obs
k     = 0.5 if (table == 0).any() else 0.0
or_s  = ((a + k) * (d + k)) / ((b + k) * (c + k))
se    = np.sqrt(1/(a+k) + 1/(b+k) + 1/(c+k) + 1/(d+k))
z     = norm.ppf(1 - alpha / 2)
woolf = np.exp(np.log(or_s) + np.array([-1, 1]) * z * se)
cond  = odds_ratio(table)             # conditional MLE, as R
ci    = cond.confidence_interval(confidence_level=1 - alpha)
phi   = (a*d - b*c) / np.sqrt(r1 * (c + d) * c1 * (b + d))

print(f"Two-sided exact p   = {res.pvalue:.4f}")
print(f"Right-tailed p      = {res_right.pvalue:.4f}")
print(f"Mid-p (two-sided)   = {mid_p:.4f}")
print(f"Sample OR (ad/bc)   = {or_s:.2f}, Woolf 95% CI {woolf[0]:.2f} to {woolf[1]:.2f}")
print(f"Conditional MLE OR  = {cond.statistic:.2f}, exact 95% CI {ci.low:.2f} to {ci.high:.2f}")
print(f"Phi                 = {phi:.2f}")
print(f"Smallest expected count = {expected_freq(table).min():.2f}")
verdict = ("evidence of an association" if res.pvalue < alpha
           else "no clear evidence of an association")
print(f"\nVerdict: p = {res.pvalue:.4f}, so there is {verdict} between group and outcome.")

# ---- 4. One 300 dpi figure ---------------------------------
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9, 4))
props = table / table.sum(axis=1, keepdims=True) * 100
ax1.barh(groups, props[:, 0], color="#16a34a", label=outcomes[0])
ax1.barh(groups, props[:, 1], left=props[:, 0], color="#f59e0b", label=outcomes[1])
ax1.set_xlabel("Percent of group"); ax1.set_title("Outcome by group")
ax1.legend(frameon=False, fontsize=8, loc="lower right")

xs = np.arange(max(0, c1 - (n - r1)), min(r1, c1) + 1)
px = rv.pmf(xs)
cols = ["#c2410c" if x == a else "#f59e0b" if p <= p_obs * (1 + 1e-7) else "#93c5fd"
        for x, p in zip(xs, px)]
ax2.bar(xs, px, color=cols)
ax2.set_xlabel("Value of cell a"); ax2.set_ylabel("Probability")
ax2.set_title(f"Exact two-sided p = {res.pvalue:.4f}")
for ax in (ax1, ax2):
    ax.spines[["top", "right"]].set_visible(False)
fig.tight_layout()
fig.savefig("fisher_plot.png", dpi=300, bbox_inches="tight")
print("Saved fisher_plot.png")

11.2 What each part does

Line or functionWhat it does
np.array([[12, 3], [3, 12]])The 2×2 table, rows = groups, columns = outcome.
fisher_exact(table)Returns the sample odds ratio (ad/bc) and the two-sided exact p-value.
alternative="greater"One-sided test that the odds ratio is above 1.
hypergeom(n, r1, c1)The exact null distribution of cell a; pmf(a) is the observed table's probability.
odds_ratio(table)The conditional MLE odds ratio with the exact CI, the same numbers R prints.
norm.ppf(1 - alpha/2)1.96 for a 95% Woolf interval.
expected_freq(table)Expected counts for the chi-square rule of thumb.
savefig(dpi=300)Print-quality output; the default 100 dpi is too low for journals.

11.3 What the figure shows

The same two panels as the R script: stacked percentages by group on the left, and the exact null distribution with your table and the counted tails marked on the right.

11.4 Common Python problems and fixes

SymptomCauseFix
Odds ratio differs from Rfisher_exact returns ad/bcUse odds_ratio(table).statistic for R's value
ImportError for odds_ratioSciPy older than 1.10pip install --upgrade scipy
Odds ratio is infA zero in b or cUse the k = 0.5 line, or report the exact CI
Crosstab rows in the wrong orderpandas sorts labelsReorder with .loc[["Treatment", "Placebo"]]
No figure appearsThe Agg backend only saves filesOpen fisher_plot.png, or add plt.show()

11.5 Useful one-liners

You wantPython code
Two-sided p onlyfisher_exact(t).pvalue
One-sided, OR below 1fisher_exact(t, alternative="less")
Exact 99% CIodds_ratio(t).confidence_interval(0.99)
Chi-square for comparisonchi2_contingency(t, correction=False)
Boschloo's exact testscipy.stats.boschloo_exact(t)
Barnard's exact testscipy.stats.barnard_exact(t)
R and Python agree exactly. Both scripts give p = 0.0028, right-tailed p = 0.0014, mid-p = 0.0021, sample OR 16.00 with Woolf CI 2.67 to 95.75, and conditional OR 14.12 with exact CI 2.11 to 139.37.

📋 12. Reference Tables

12.1 Every possible table for the drug trial (margins 15, 15, 15, 15)

a*Table (a, b, c, d)P(a*)Two-sided sum
00, 15, 15, 00.000000✓ counted
11, 14, 14, 10.000001✓ counted
22, 13, 13, 20.000071✓ counted
33, 12, 12, 30.001335✓ counted
44, 11, 11, 40.012012not counted
55, 10, 10, 50.058137not counted
66, 9, 9, 60.161491not counted
77, 8, 8, 70.266954not counted
88, 7, 7, 80.266954not counted
99, 6, 6, 90.161491not counted
1010, 5, 5, 100.058137not counted
1111, 4, 4, 110.012012not counted
1212, 3, 3, 120.001335✓ counted
1313, 2, 2, 130.000071✓ counted
1414, 1, 1, 140.000001✓ counted
1515, 0, 0, 150.000000✓ counted

Conclusion: the eight counted tables add to p = 0.002814. The observed table (a* = 12) and its mirror (a* = 3) each have P = 0.001335.

12.2 The smallest samples that can ever be significant

Perfect splitTableTwo-sided pBelow 0.05?
2 vs 22, 0, 0, 20.3333No
3 vs 33, 0, 0, 30.1000No
4 vs 44, 0, 0, 40.0286Yes
5 vs 55, 0, 0, 50.0079Yes
6 vs 66, 0, 0, 60.0022Yes
7 vs 77, 0, 0, 70.0006Yes

Conclusion: with 3 or fewer per group, no result can reach p < 0.05, however strong. Plan at least 4 per group, and many more for realistic effects.

12.3 Fisher vs chi-square on the same tables

Table (a, b, c, d)Min expectedFisher pChi-square pYates p
12, 3, 3, 127.500.00280.00100.0035
11, 2, 5, 74.320.04140.02540.0690
7, 9, 2, 144.500.11340.04930.1158
5, 1, 1, 53.000.08010.02090.0833
3, 1, 1, 32.000.48570.15730.4795
0, 20, 5, 152.500.04710.01680.0558

Conclusion: with small expected counts, uncorrected chi-square gives smaller p-values than Fisher, and twice (7, 9, 2, 14 and 5, 1, 1, 5) it crosses 0.05 when Fisher does not.

12.4 Interpretation bands

StatisticValueReading
p-valuebelow 0.001 / 0.01 / 0.05Very strong / strong / moderate evidence
Odds ratio1No association
Odds ratio1.5, 2.5, 4.3 (or 0.67, 0.40, 0.23)Roughly small, medium, large (Chen et al. style rule of thumb)
|φ|0.10 / 0.30 / 0.50Small / medium / large (Cohen)
Minimum expected countbelow 5Prefer Fisher over chi-square

Conclusion: always read the p-value with the odds ratio and its CI. A tiny p with OR near 1 is a trivial effect.

12.5 Which test for which design?

DesignUseWhy
Two independent groups, yes/no, small nFisher's exact testExact for any sample size
Two independent groups, all expected ≥ 5Chi-square or FisherBoth give similar p
Small trial, only group sizes fixedBarnard's or Boschloo's testUnconditional, more power
Same subjects twice (before/after)McNemar's testPaired data
More than two groups or outcomesFisher-Freeman-Halton (this calculator, up to 8×8)r×c table
Several 2×2 tables (strata)Cochran-Mantel-HaenszelAdjusts for a confounder

Conclusion: Fisher is the safe default for one small 2×2 table of independent subjects.

12.6 What each program reports

SoftwareOdds ratio shownConfidence intervalTwo-sided rule
R fisher.testConditional MLEExact conditionalSum of tables with P ≤ P(obs)
SciPy fisher_exactSample ad/bcNone (use odds_ratio)Same as R
SPSS CrosstabsSample OR (Risk Estimate)Woolf-typeSame as R
SAS PROC FREQ (EXACT FISHER OR)Sample ORExactSame as R
ExcelBuild it yourselfBuild it yourselfBuild with SUMIF (Section 9)
This calculatorBothWoolf or exactSame as R

Conclusion: p-values agree everywhere; odds ratios and intervals differ by method, so always name the method.

📈 13. Example Results: 8 Fisher's Exact Test Examples

Each example was computed with SciPy 1.18 and matches R. Type any table into the Manual 2×2 tab to check it.

1
TEXTBOOK CASE

Lady tasting tea

Fisher's own 1935 example: impressive guesses, weak evidence.

Milk first vs Tea first, outcome: said milk first. n = 8.

n = 8p = 0.4857OR = 9.00φ = 0.50not significant
StatisticValueNote
Table (a, b, c, d)3, 1, 1, 3Milk first then Tea first
% said milk first75.0% vs 25.0%Group 1 vs group 2
Two-sided p0.4857Fisher exact
Right / left p0.2429 / 0.9857One-sided
Mid-p0.3714Less conservative
Sample OR9.00ad ÷ bc
Conditional MLE OR6.41As R prints
Exact 95% CI0.21 to 626.24As R prints
Woolf 95% CI0.37 to 220.93+0.5 if any zero
Chi-square p0.1573Min expected 2.00
Said milk first: 75.0% in Milk first vs 25.0% in Tea first, Fisher p = 0.4857Milk first75.0%Tea first25.0%Percent said milk firstTwo-sided Fisher p = 0.4857 · n = 8
Percent said milk first in each group.

What it means: Three of four cups right sounds impressive, but with 8 cups there are only 70 ways to choose which 4 had milk first, and getting 3 right happens by luck about half the time. The test says p = 0.4857: no evidence she could tell.

How to write it: "Correct identification was not better than chance (3/4 vs 1/4), Fisher's exact test p = .486."

2
CLEARLY SIGNIFICANT

Drug trial cure rates

A strong effect in a small trial.

Treatment vs Placebo, outcome: cured. n = 30.

n = 30p = 0.0028OR = 16.00φ = 0.60significant
StatisticValueNote
Table (a, b, c, d)12, 3, 3, 12Treatment then Placebo
% cured80.0% vs 20.0%Group 1 vs group 2
Two-sided p0.0028Fisher exact
Right / left p0.0014 / 0.9999One-sided
Mid-p0.0021Less conservative
Sample OR16.00ad ÷ bc
Conditional MLE OR14.12As R prints
Exact 95% CI2.11 to 139.37As R prints
Woolf 95% CI2.67 to 95.75+0.5 if any zero
Chi-square p0.0010Min expected 7.50
Cured: 80.0% in Treatment vs 20.0% in Placebo, Fisher p = 0.0028Treatment80.0%Placebo20.0%Percent curedTwo-sided Fisher p = 0.0028 · n = 30
Percent cured in each group.

What it means: Cure rates of 80% vs 20% in 30 patients are very unlikely by chance (p = 0.0028). The CI is wide (2.67 to 95.75) because the trial is small, so the true effect could be moderate or huge, but it is clearly above 1.

How to write it: "Cure rates were higher with treatment (80.0%, 12/15) than placebo (20.0%, 3/15), Fisher's exact test p = .003, OR = 16.00, 95% CI [2.67, 95.75]."

3
BORDERLINE

Teaching method pass rates

p just under 0.05, but the exact CI touches 1.

New method vs Traditional, outcome: pass. n = 25.

n = 25p = 0.0414OR = 7.70φ = 0.45significant
StatisticValueNote
Table (a, b, c, d)11, 2, 5, 7New method then Traditional
% pass84.6% vs 41.7%Group 1 vs group 2
Two-sided p0.0414Fisher exact
Right / left p0.0335 / 0.9967One-sided
Mid-p0.0263Less conservative
Sample OR7.70ad ÷ bc
Conditional MLE OR7.02As R prints
Exact 95% CI0.90 to 93.44As R prints
Woolf 95% CI1.16 to 51.17+0.5 if any zero
Chi-square p0.0254Min expected 4.32
Pass: 84.6% in New method vs 41.7% in Traditional, Fisher p = 0.0414New method84.6%Traditional41.7%Percent passTwo-sided Fisher p = 0.0414 · n = 25
Percent pass in each group.

What it means: p = 0.0414 is below 0.05, yet the exact CI (0.90 to 93.44) includes 1. The two rules define 'extreme' differently, so near the cut-off they disagree. Treat this as borderline and report both numbers.

How to write it: "Pass rates were higher with the new method (84.6%) than the traditional method (41.7%), Fisher's exact test p = .041, conditional OR = 7.02, exact 95% CI [0.90, 93.44]."

4
NULL RESULT

Nest predation, fenced vs open plots

No evidence of a difference, and a very wide CI.

Fenced vs Open, outcome: predated. n = 20.

n = 20p = 1.0000OR = 0.58φ = -0.12not significant
StatisticValueNote
Table (a, b, c, d)2, 8, 3, 7Fenced then Open
% predated20.0% vs 30.0%Group 1 vs group 2
Two-sided p1.0000Fisher exact
Right / left p0.8483 / 0.5000One-sided
Mid-p0.8259Less conservative
Sample OR0.58ad ÷ bc
Conditional MLE OR0.60As R prints
Exact 95% CI0.04 to 6.94As R prints
Woolf 95% CI0.07 to 4.56+0.5 if any zero
Chi-square p0.6056Min expected 2.50
Predated: 20.0% in Fenced vs 30.0% in Open, Fisher p = 1.0000Fenced20.0%Open30.0%Percent predatedTwo-sided Fisher p = 1.0000 · n = 20
Percent predated in each group.

What it means: 20% vs 30% predation with 10 plots each gives p = 1.0000. The CI runs from 0.04 to 6.94, so the data fit anything from a big protective effect to a big harmful one. This is an underpowered study, not proof of no effect.

How to write it: "Predation did not differ between fenced (20%) and open plots (30%), Fisher's exact test p = 1.000, OR = 0.58, 95% CI [0.07, 4.56]."

5
SMALL SAMPLE

Pilot surgery, 6 patients per arm

Chi-square says significant. Fisher says not yet.

New technique vs Standard, outcome: healed. n = 12.

n = 12p = 0.0801OR = 25.00φ = 0.67not significant
StatisticValueNote
Table (a, b, c, d)5, 1, 1, 5New technique then Standard
% healed83.3% vs 16.7%Group 1 vs group 2
Two-sided p0.0801Fisher exact
Right / left p0.0400 / 0.9989One-sided
Mid-p0.0606Less conservative
Sample OR25.00ad ÷ bc
Conditional MLE OR16.60As R prints
Exact 95% CI0.80 to 1410.23As R prints
Woolf 95% CI1.20 to 520.73+0.5 if any zero
Chi-square p0.0209Min expected 3.00
Healed: 83.3% in New technique vs 16.7% in Standard, Fisher p = 0.0801New technique83.3%Standard16.7%Percent healedTwo-sided Fisher p = 0.0801 · n = 12
Percent healed in each group.

What it means: 83% vs 17% looks dramatic, and uncorrected chi-square says p = 0.0209. Fisher gives p = 0.0801, because with expected counts of 3 the chi-square shortcut fails. Six per arm is too few to conclude anything.

How to write it: "Healing was 83.3% with the new technique and 16.7% with the standard one, but the difference was not significant, Fisher's exact test p = .080."

6
SIGNIFICANT BUT TRIVIAL

Appointment reminders, 2,000 patients

Large n makes a tiny difference significant.

SMS reminder vs Letter, outcome: attended. n = 2000.

n = 2000p = 0.0284OR = 1.22φ = 0.05significant
StatisticValueNote
Table (a, b, c, d)520, 480, 470, 530SMS reminder then Letter
% attended52.0% vs 47.0%Group 1 vs group 2
Two-sided p0.0284Fisher exact
Right / left p0.0142 / 0.9887One-sided
Mid-p0.0269Less conservative
Sample OR1.22ad ÷ bc
Conditional MLE OR1.22As R prints
Exact 95% CI1.02 to 1.46As R prints
Woolf 95% CI1.02 to 1.46+0.5 if any zero
Chi-square p0.0253Min expected 495.00
Attended: 52.0% in SMS reminder vs 47.0% in Letter, Fisher p = 0.0284SMS reminder52.0%Letter47.0%Percent attendedTwo-sided Fisher p = 0.0284 · n = 2000
Percent attended in each group.

What it means: With 1,000 per group, 52% vs 47% attendance is significant (p = 0.0284), but phi is only 0.05 and the OR is 1.22. The effect is real but small. Judge it by the 5-point risk difference, not by the p-value.

How to write it: "Attendance was slightly higher after SMS reminders (52.0% vs 47.0%), Fisher's exact test p = .028, OR = 1.22, 95% CI [1.02, 1.46], φ = 0.05."

7
ASSUMPTION STRESS

Rare side effect with a zero cell

A zero cell breaks the simple odds ratio, not the test.

Drug vs Control, outcome: side effect. n = 40.

n = 40p = 0.0471OR = 0.00φ = -0.38significant
StatisticValueNote
Table (a, b, c, d)0, 20, 5, 15Drug then Control
% side effect0.0% vs 25.0%Group 1 vs group 2
Two-sided p0.0471Fisher exact
Right / left p1.0000 / 0.0236One-sided
Mid-p0.0353Less conservative
Sample OR0.00ad ÷ bc
Conditional MLE OR0.00As R prints
Exact 95% CI0.00 to 0.98As R prints
Woolf 95% CI0.00 to 1.34+0.5 if any zero
Chi-square p0.0168Min expected 2.50
Side effect: 0.0% in Drug vs 25.0% in Control, Fisher p = 0.0471Drug0.0%Control25.0%Percent side effectTwo-sided Fisher p = 0.0471 · n = 40
Percent side effect in each group.

What it means: A zero cell makes ad/bc equal 0 and the Woolf CI needs a 0.5 correction (0.0035 to 1.3388, which includes 1). The exact CI (0 to 0.98) and the test (p = 0.0471) both work without any fix and agree.

How to write it: "No side effects occurred with the drug (0/20) compared with 5/20 controls, Fisher's exact test p = .047, conditional OR = 0.00, exact 95% CI [0.00, 0.98]."

8
APPLIED FIELD STUDY

Camera traps in two forest patches

Detection differs clearly between habitats.

Forest A vs Forest B, outcome: detected. n = 24.

n = 24p = 0.0123OR = 15.00φ = 0.59significant
StatisticValueNote
Table (a, b, c, d)10, 2, 3, 9Forest A then Forest B
% detected83.3% vs 25.0%Group 1 vs group 2
Two-sided p0.0123Fisher exact
Right / left p0.0061 / 0.9997One-sided
Mid-p0.0094Less conservative
Sample OR15.00ad ÷ bc
Conditional MLE OR12.93As R prints
Exact 95% CI1.54 to 190.98As R prints
Woolf 95% CI2.02 to 111.17+0.5 if any zero
Chi-square p0.0041Min expected 5.50
Detected: 83.3% in Forest A vs 25.0% in Forest B, Fisher p = 0.0123Forest A83.3%Forest B25.0%Percent detectedTwo-sided Fisher p = 0.0123 · n = 24
Percent detected in each group.

What it means: Detection at 83% of stations in Forest A vs 25% in Forest B gives p = 0.0123. Each station counts once, so the observations are independent. Repeat photos at one station must not be counted separately.

How to write it: "Detection was higher in Forest A (10/12 stations) than Forest B (3/12), Fisher's exact test p = .012, conditional OR = 12.93, exact 95% CI [1.54, 190.98]."

🧪 14. Data Collection Protocol

Study design: Fisher's exact test needs independent subjects, each classified once by group (two levels) and by outcome (two levels).

  1. Define the two groups before you collect data, for example treatment and placebo.
  2. Define the outcome as yes/no with a written rule, for example "cured = no symptoms at day 14".
  3. Choose the unit of observation: one patient, one plot, one camera station. Count each unit once.
  4. Randomise group assignment where you can, so the test reflects the treatment and not who was picked.
  5. Blind the outcome assessor to group, so the yes/no call is not biased.
  6. Record missing outcomes as blank, never as 0, and report how many were missing in each group.
  7. Plan the sample size with a power calculation for your smallest important difference.
  8. Pre-register the direction if you will use a one-tailed test.
  9. Store one row per unit with group and outcome columns (layout below).
  10. Check the 2×2 counts against your raw sheet before running the test.
Unit IDGroupOutcome (1 = event)
P001Treatment1
P002Placebo0
P003Treatment1

Minimum sample: at least 4 per group before any result can reach p < 0.05 (Table 12.2). For an odds ratio near 4 with 80% power, plan roughly 40 to 60 per group.

Pre-registration line: "The primary analysis is a two-sided Fisher's exact test at α = 0.05, reporting the odds ratio with its exact 95% CI."

Common mistakes: counting repeat measurements as separate units, recoding missing outcomes as 0, and choosing a one-tailed test after seeing the data.

🎯 15. When to Use Fisher's Exact Test

Use it when

  • You have two independent groups and a yes/no outcome.
  • Any expected count is below 5, or n is small.
  • You want an exact p-value and an odds ratio with a CI.
  • A cell is zero or the table is very unbalanced.

Do not use it when

  • The same subjects are measured twice: use McNemar's test.
  • The outcome is a measurement: use a t-test or Mann-Whitney test.
  • You need to adjust for a confounder: use Cochran-Mantel-Haenszel or logistic regression.
  • Observations are clustered (pupils within schools): use a mixed model.

Four examples

  • Medicine: cure in 12/15 treated vs 3/15 placebo patients.
  • Public health: infection in vaccinated vs unvaccinated people in a small outbreak.
  • Ecology: species detected at camera stations in two forest patches.
  • Marketing: purchases after email A vs email B in a small test.

Decision tree

  1. Is the outcome yes/no? If not, use a test for measurements.
  2. Are the groups independent? If not, use McNemar's test.
  3. Is the table 2×2? If not, use the Fisher-Freeman-Halton exact test: add rows or columns on the Manual Table tab above.
  4. Is any expected count below 5? If yes, use Fisher's exact test. If no, Fisher or chi-square both work.

🔧 16. Troubleshooting and Common Errors

The Run button shows an error about 0 or 1

Cause: A value other than 0 or 1 is in a group box.

Fix: Remove text, blanks typed as words, or codes like 2; use 1 for the event and 0 for none.

A row or column total is zero

Cause: One group had no subjects, or nobody had the outcome.

Fix: Fisher cannot test a table with an empty margin; check the data.

The odds ratio is 0 or infinite

Cause: A zero in cell a, b, c or d.

Fix: Use the Woolf CI (adds 0.5) or switch to the exact CI, which needs no correction.

My odds ratio differs from R

Cause: R prints the conditional MLE.

Fix: Choose Exact conditional in Step 2 to match R.

p is significant but the exact CI includes 1

Cause: Test and CI use different two-sided rules.

Fix: Report both; see Section 4.8 and Fay (2010).

Chi-square gave p below 0.05 but Fisher does not

Cause: Expected counts below 5 make chi-square too liberal.

Fix: Report Fisher; see Table 12.3.

Upload shows no columns

Cause: The columns contain text such as Yes/No.

Fix: Recode to 1 and 0 before uploading.

p-value is exactly 1

Cause: The observed table is the most likely one.

Fix: Normal for very balanced tables; report p = 1.000.

Results disappeared

Cause: You changed the sample dataset.

Fix: Switching datasets clears results; press Run again.

Charts do not appear

Cause: The chart library was blocked by the network or an ad blocker.

Fix: Allow cdnjs.cloudflare.com, then press Run again.

⚖ 17. Assumptions and Limitations

Assumptions

  1. Independent observations. Check: each unit appears once. If broken (repeat measures counted separately), p is too small: false positives.
  2. Binary variables. Check: exactly two groups and two outcomes. If you merge categories after looking, p is biased toward significance.
  3. Fixed margins. The test conditions on row and column totals. When only group sizes were fixed (most trials), the test is conservative: p is too large and power is lost.
  4. Counts, not percentages. Check: whole numbers. Entering percentages inflates n and makes p far too small.

Limitations

  • Conservative in small trials. Alternative: mid-p, or Barnard's or Boschloo's unconditional test.
  • Shows association, not causation. Alternative: a randomised design.
  • Cannot adjust for confounders. Alternative: Cochran-Mantel-Haenszel or logistic regression.
  • Odds ratios, RR and phi are shown only for 2×2 tables. For larger tables the calculator gives the exact p-value, Cramér's V and adjusted residuals.
  • Low power with very small n. Alternative: plan a larger sample with a power analysis.

🏁 18. Conclusion

A Fisher's exact test calculator answers one question well: are two yes/no variables linked in a small 2×2 table? It does so without the large-sample shortcut that makes chi-square unreliable when expected counts fall below 5.

The p-value tells you how surprising the table is if there were no link. The odds ratio and its confidence interval tell you how big the link is and how sure you can be. Report all three, and name the odds ratio and CI method so readers can match your numbers in R, Python or SPSS.

Run the test to see a conclusion written from your own numbers: p = ___, OR = ___, 95% CI ___.

Keep the limits in mind. The test needs independent subjects, it can be conservative, and a non-significant result in a small study is not proof of no effect. Come back to this Fisher's exact test calculator whenever you have a small or sparse 2×2 table.

❓ 19. Frequently Asked Questions

Q1. What is Fisher's exact test?

Fisher's exact test is a significance test for a 2×2 contingency table. It asks whether two categorical variables, each with two levels, are independent. Instead of a chi-square approximation, it sums exact hypergeometric probabilities of tables with the same row and column totals, so the p-value is exact for any sample size.

Q2. When should I use Fisher's exact test instead of chi-square?

Use Fisher's exact test when any expected cell count is below 5, when the total sample is small (roughly under 40), or when the table is sparse or unbalanced. With large samples and all expected counts of 5 or more, chi-square and Fisher give almost the same p-value, so either is fine.

Q3. How do I use this Fisher's exact test calculator?

Pick a sample dataset or type your own data. You can paste 0/1 outcomes for each group, upload a CSV or Excel file, or type the four counts a, b, c and d into the Manual 2×2 tab. Choose alpha, the tail and the CI method, then press Run. Results, charts and an APA sentence appear below.

Q4. How do you calculate Fisher's exact test by hand?

Find the row totals, column totals and n. Compute the probability of your table with P = C(a+b, a) × C(c+d, c) / C(n, a+c). Repeat for every possible value of cell a with the same margins. The two-sided p-value is the sum of all probabilities that are less than or equal to your table's probability.

Q5. What does the p-value from Fisher's exact test mean?

It is the probability of getting a table at least as extreme as yours if the two variables were truly independent. A p-value of 0.0028 means a result this lopsided would happen about 3 times in 1,000 by chance alone. It is not the probability that the null hypothesis is true.

Q6. What is the null hypothesis of Fisher's exact test?

The null hypothesis is that the two variables are independent, which means the odds ratio equals 1 and the proportion with the outcome is the same in both groups. The alternative is that the odds ratio is not 1 (two-sided), greater than 1 (right-tailed) or less than 1 (left-tailed).

Q7. Should I use a one-tailed or two-tailed Fisher's exact test?

Use the two-tailed test unless you wrote down a directional hypothesis before seeing the data. The one-tailed p-value is smaller, so picking it after looking at the results inflates false positives. Journals and reviewers expect two-sided Fisher p-values by default.

Q8. Why does the odds ratio differ between this calculator and R?

R's fisher.test() reports the conditional maximum likelihood odds ratio, not the simple ad/bc ratio. For 12, 3, 3, 12 the sample OR is 16.00 while R prints 14.12. This calculator shows both. Choose the Exact conditional CI method to match R's confidence interval.

Q9. How do I interpret the odds ratio from Fisher's exact test?

An odds ratio of 1 means no association. Above 1, the first group has higher odds of the outcome; below 1, lower odds. If the confidence interval excludes 1 the association is significant at that level. Always report the interval, because small samples give wide, uncertain estimates.

Q10. Can Fisher's exact test handle a zero in a cell?

Yes. The exact p-value and the exact conditional confidence interval work with zero cells. The sample odds ratio becomes 0 or infinite, so the Woolf interval adds 0.5 to every cell (Haldane-Anscombe correction). The example 0, 20, 5, 15 still gives a valid two-sided p = 0.0471.

Q11. How do I report Fisher's exact test in APA 7 format?

Write the test, the proportions and the statistics in one sentence: “Cure rates were higher with treatment (80.0%, 12/15) than placebo (20.0%, 3/15), Fisher's exact test p = .003, OR = 16.00, 95% CI [2.67, 95.75].” Italicise p, give it to three decimals, and use p < .001 for very small values.

Q12. How do I run Fisher's exact test in R?

Build a matrix and call fisher.test(): fisher.test(matrix(c(12, 3, 3, 12), nrow = 2, byrow = TRUE)). R prints the two-sided p-value, the conditional MLE odds ratio and its 95% exact confidence interval. Add alternative = "greater" or "less" for a one-sided test.

Q13. How do I run Fisher's exact test in Python?

Use SciPy: from scipy.stats import fisher_exact, then fisher_exact([[12, 3], [3, 12]]). It returns the sample odds ratio and the p-value. For the exact conditional CI that matches R, use scipy.stats.contingency.odds_ratio(table).confidence_interval().

Q14. Can I do Fisher's exact test in Excel?

Excel has no Fisher button, but HYPGEOM.DIST does the work. List every possible value of cell a, get each probability with =HYPGEOM.DIST(a, row1, col1, n, FALSE), then use SUMIF to add the probabilities that are less than or equal to the observed one. The Excel section on this page gives the exact formulas.

Q15. How do I get Fisher's exact test in SPSS?

Go to Analyze, Descriptive Statistics, Crosstabs. Put one variable in Rows and the other in Columns, click Statistics and tick Chi-square. SPSS prints Fisher's Exact Test automatically for 2×2 tables, with exact two-sided and one-sided significance values.

Q16. What are the assumptions of Fisher's exact test?

Each subject appears in exactly one cell, observations are independent, both variables are binary, and the analysis conditions on the row and column totals. The test needs no minimum sample size. Paired or repeated yes/no data break the independence assumption and need McNemar's test.

Q17. Is Fisher's exact test too conservative?

Often, yes. Because the hypergeometric distribution is discrete, the real false-positive rate is usually below alpha. The mid-p value, also shown by this calculator, reduces that conservatism. Barnard's and Boschloo's unconditional tests are more powerful alternatives for small 2×2 trials.

Q18. Can Fisher's exact test be used for tables larger than 2×2?

Yes. The Fisher-Freeman-Halton extension handles r × c tables, and this calculator runs it: on the Manual Table tab, press Add row or Add column (up to 8 × 8). Small tables are enumerated exactly; very large ones use a seeded Monte Carlo estimate, like R's fisher.test(simulate.p.value = TRUE). Odds ratios apply only to 2 × 2 tables, so larger tables report Cramér's V and adjusted residuals instead.

Q19. What sample size do I need for Fisher's exact test?

There is no minimum, but power is low in tiny samples. Detecting an odds ratio near 4 with 80% power at alpha 0.05 usually needs about 40 to 60 subjects per group, depending on the baseline rate. Run a power analysis before collecting data.

Q20. What should I do if my Fisher's exact test result is not significant?

A non-significant result does not prove independence. Look at the odds ratio and its confidence interval: a wide interval that includes large effects means the study was underpowered. Report the estimate honestly, avoid switching to a one-tailed test, and plan a larger sample.

📑 20. Cite This Tool

APA 7th edition
StatsUnlock. (2026). Fisher's exact test calculator [Interactive statistical tool]. https://statsunlock.com/fishers-exact-test-calculator/
BibTeX
@misc{statsunlock_fisher_2026, title={Fisher's Exact Test Calculator}, author={{StatsUnlock}}, year={2026}, note={Interactive statistical tool}, url={https://statsunlock.com/fishers-exact-test-calculator/}}
Methods wording
The association between group and outcome was tested with a two-sided Fisher's exact test (alpha = 0.05) using the StatsUnlock Fisher's Exact Test Calculator (2026). We report the exact p-value, the odds ratio with its 95% confidence interval, and phi as the effect size. Results were confirmed with R's fisher.test().

🔗 21. Related Tools

📖 22. Glossary of Terms

TermPlain-English meaning
2×2 contingency tableA table of counts for two yes/no variables, with four cells called a, b, c and d.
Alternative hypothesisThe claim that the two variables are linked, so the odds ratio is not 1.
Cell countThe number of subjects in one box of the table.
Conditional MLE odds ratioThe odds ratio that best fits the hypergeometric model. R prints this one.
Confidence intervalA range of odds ratios that fit the data. A 95% interval misses the true value in about 5% of studies.
Conservative testA test whose real false-positive rate is below the alpha you chose. Fisher's test often is.
Exact (Cornfield) CIA confidence interval for the odds ratio found by inverting the exact test.
Exact p-valueA p-value computed straight from the sampling distribution, with no large-sample shortcut.
Expected countThe count a cell would have if the variables were unrelated: row total × column total ÷ n.
Haldane-Anscombe correctionAdding 0.5 to every cell so the odds ratio stays defined when a cell is zero.
Hypergeometric distributionThe probability model for cell a when all four margins are fixed.
IndependenceTwo variables are independent when knowing one tells you nothing about the other.
Marginal totalsThe row totals and column totals of the table. Fisher's test holds them fixed.
McNemar's testThe test for paired yes/no data, such as the same people before and after.
Mid-p valueThe exact p-value minus half the probability of the observed table. Less conservative.
Null hypothesisThe claim that the two variables are independent, so the odds ratio equals 1.
OddsThe chance of an event divided by the chance of no event. 12 cured and 3 not cured gives odds of 4.
Odds ratio (OR)The odds in group 1 divided by the odds in group 2. 1 means no association.
One-tailed testA test that looks for a difference in one stated direction only.
Phi coefficient (φ)A correlation for 2×2 tables, from −1 to 1. Bands: 0.10 small, 0.30 medium, 0.50 large.
Relative risk (RR)The proportion with the outcome in group 1 divided by the proportion in group 2.
Two-tailed testA test that looks for a difference in either direction. The default for research.
Woolf CIA confidence interval for the odds ratio built on the log scale with SE = √(1/a + 1/b + 1/c + 1/d).

📚 23. References

These peer-reviewed sources support the methods in this Fisher's exact test calculator: the exact p-value, the odds ratio intervals, mid-p, and when to prefer Fisher over chi-square.

  1. Fisher, R. A. (1922). On the interpretation of χ² from contingency tables, and the calculation of P. Journal of the Royal Statistical Society, 85(1), 87–94. https://doi.org/10.2307/2340521
  2. Fisher, R. A. (1935). The logic of inductive inference. Journal of the Royal Statistical Society, 98(1), 39–82. https://doi.org/10.2307/2342435
  3. Yates, F. (1934). Contingency tables involving small numbers and the χ² test. Supplement to the Journal of the Royal Statistical Society, 1(2), 217–235. https://doi.org/10.2307/2983604
  4. Freeman, G. H., & Halton, J. H. (1951). Note on an exact treatment of contingency, goodness of fit and other problems of significance. Biometrika, 38(1/2), 141–149. https://doi.org/10.2307/2332323
  5. Barnard, G. A. (1945). A new test for 2 × 2 tables. Nature, 156, 177. https://doi.org/10.1038/156177a0
  6. Woolf, B. (1955). On estimating the relation between blood group and disease. Annals of Human Genetics, 19(4), 251–253. https://doi.org/10.1111/j.1469-1809.1955.tb01348.x
  7. Haldane, J. B. S. (1956). The estimation and significance of the logarithm of a ratio of frequencies. Annals of Human Genetics, 20(4), 309–311. https://doi.org/10.1111/j.1469-1809.1955.tb01285.x
  8. Lancaster, H. O. (1961). Significance tests in discrete distributions. Journal of the American Statistical Association, 56(294), 223–234. https://doi.org/10.1080/01621459.1961.10482107
  9. Upton, G. J. G. (1982). A comparison of alternative tests for the 2 × 2 comparative trial. Journal of the Royal Statistical Society A, 145(1), 86–105. https://doi.org/10.2307/2981423
  10. Mehta, C. R., & Patel, N. R. (1983). A network algorithm for performing Fisher's exact test in r × c contingency tables. Journal of the American Statistical Association, 78(382), 427–434. https://doi.org/10.1080/01621459.1983.10477989
  11. Agresti, A. (1992). A survey of exact inference for contingency tables. Statistical Science, 7(1), 131–153. https://doi.org/10.1214/ss/1177011454
  12. Agresti, A. (2001). Exact inference for categorical data: Recent advances and continuing controversies. Statistics in Medicine, 20(17–18), 2709–2722. https://doi.org/10.1002/sim.738
  13. Bland, J. M., & Altman, D. G. (2000). The odds ratio. BMJ, 320(7247), 1468. https://doi.org/10.1136/bmj.320.7247.1468
  14. Campbell, I. (2007). Chi-squared and Fisher-Irwin tests of two-by-two tables with small sample recommendations. Statistics in Medicine, 26(19), 3661–3675. https://doi.org/10.1002/sim.2832
  15. Crans, G. G., & Shuster, J. J. (2008). How conservative is Fisher's exact test? A quantitative evaluation of the two-sample comparative binomial trial. Statistics in Medicine, 27(18), 3598–3611. https://doi.org/10.1002/sim.3221
  16. Ludbrook, J. (2008). Analysis of 2 × 2 tables of frequencies: Matching test to experimental design. International Journal of Epidemiology, 37(6), 1430–1435. https://doi.org/10.1093/ije/dyn162
  17. Lydersen, S., Fagerland, M. W., & Laake, P. (2009). Recommended tests for association in 2 × 2 tables. Statistics in Medicine, 28(7), 1159–1175. https://doi.org/10.1002/sim.3531
  18. Fay, M. P. (2010). Confidence intervals that match Fisher's exact or Blaker's exact tests. Biostatistics, 11(2), 373–374. https://doi.org/10.1093/biostatistics/kxp050
  19. Kim, H.-Y. (2017). Statistical notes for clinical researchers: Chi-squared test and Fisher's exact test. Restorative Dentistry & Endodontics, 42(2), 152–155. https://doi.org/10.5395/rde.2017.42.2.152
  20. Virtanen, P., Gommers, R., Oliphant, T. E., et al. (2020). SciPy 1.0: Fundamental algorithms for scientific computing in Python. Nature Methods, 17, 261–272. https://doi.org/10.1038/s41592-020-0772-5
STATS UNLOCK · statsunlock.com · Fisher's Exact Test Calculator
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Statistical Models

Important Plots & Charts

Calculators and Converters