Skip to content

EGenetics · genetics.mk

McDonald–Kreitman test

Is the ratio of protein-changing to silent changes the same within species as between them?

Builds the 2 × 2 table of nonsynonymous and synonymous differences that are polymorphic within a species (P_N, P_S) or fixed between species (D_N, D_S). Under neutrality the two ratios match. Reports Fisher's exact test (or G / χ²), the neutrality index NI, the share of adaptive substitutions α = 1 − NI, the direction of selection, and α across genes (Stoletzki and Eyre-Walker 2011) when there are several. Slightly deleterious polymorphisms and demography bias α, so a significant table isn't proof of adaptation. Research use only.

Experimental Python and R agree to 10 decimals Also called McDonald-Kreitman test, MK test, McDonald Kreitman…

A real result

Example “Guide fisher”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

McDonald–Kreitman testRecorded · Python and R agreeRecorded 2026-11-17 · 27 values compared
R

McDonald–Kreitman test, P_N = 12, P_S = 30, D_N = 8, D_S = 40, p = .209, NI = 2.00

Neutrality index NI
2
α (adaptive substitutions)
−1
Direction of selection DoS
−0.1190
p (Fisher's exact test)
.209

Effect size

  • Neutrality index (conditional odds ratio) 1.984 95% CI [0.6510, 6.363]

Assumptions

  • Expected counts ≥ 5 (G and χ²) — Fisher's test conditions on the margins; the smallest expected count is 9.33.
  • Synonymous sites are neutral — Not checkable from counts: strong codon bias would break the yardstick.
  • Few slightly deleterious polymorphisms — NI above 1: an excess of protein-changing polymorphism, the signature of slightly deleterious variants that bias α downwards.
  • Correct orthology and site classes — Assumed: one outgroup, polymorphic and fixed sites called correctly.

McDonald–Kreitman table

NonsynonymousSynonymous
Polymorphic1230
Fixed840

Tests of the summed table

TestStatisticp
Fisher's exact (two-sided)—0.2094
G-test1.8390.1751
Pearson χ²1.8370.1753
  • Research use only: not for clinical or diagnostic decisions. Genotypes are personal data.
  • NI = (P_N/P_S)/(D_N/D_S): above 1 points to slightly deleterious polymorphism, below 1 to adaptive substitution; α = 1 − NI.
  • Conditional odds ratio 1.984 (95% exact CI 0.651 to 6.363) estimates NI from the table.
  • Odds-ratio direction: the headline odds ratio is polymorphic over fixed (NI orientation, (P_N/P_S)/(D_N/D_S)). The reference's MK odds ratio is fixed over polymorphic, its reciprocal: reported as or_reference (sample) and or_reference_cmle (conditional). One-sided Fisher p: 'less' tests NI < 1 (adaptive substitution), 'greater' tests NI > 1.
Python

McDonald–Kreitman test, P_N = 12, P_S = 30, D_N = 8, D_S = 40, p = .209, NI = 2.00

Neutrality index NI
2
α (adaptive substitutions)
−1
Direction of selection DoS
−0.1190
p (Fisher's exact test)
.209

Effect size

  • Neutrality index (conditional odds ratio) 1.984 95% CI [0.6510, 6.363]

Assumptions

  • Expected counts ≥ 5 (G and χ²) — Fisher's test conditions on the margins; the smallest expected count is 9.33.
  • Synonymous sites are neutral — Not checkable from counts: strong codon bias would break the yardstick.
  • Few slightly deleterious polymorphisms — NI above 1: an excess of protein-changing polymorphism, the signature of slightly deleterious variants that bias α downwards.
  • Correct orthology and site classes — Assumed: one outgroup, polymorphic and fixed sites called correctly.

McDonald–Kreitman table

NonsynonymousSynonymous
Polymorphic1230
Fixed840

Tests of the summed table

TestStatisticp
Fisher's exact (two-sided)—0.2094
G-test1.8390.1751
Pearson χ²1.8370.1753
  • Research use only: not for clinical or diagnostic decisions. Genotypes are personal data.
  • NI = (P_N/P_S)/(D_N/D_S): above 1 points to slightly deleterious polymorphism, below 1 to adaptive substitution; α = 1 − NI.
  • Conditional odds ratio 1.984 (95% exact CI 0.651 to 6.363) estimates NI from the table.
  • Odds-ratio direction: the headline odds ratio is polymorphic over fixed (NI orientation, (P_N/P_S)/(D_N/D_S)). The reference's MK odds ratio is fixed over polymorphic, its reciprocal: reported as or_reference (sample) and or_reference_cmle (conditional). One-sided Fisher p: 'less' tests NI < 1 (adaptive substitution), 'greater' tests NI > 1.

Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.

Worked examples in the app

  • Guide fisherge_mk_guide · dn: dn · ds: ds · pn: pn · ps: ps
  • Guide gge_mk_guide · dn: dn · ds: ds · pn: pn · ps: ps
  • Guide chisqge_mk_guide · dn: dn · ds: ds · gene: gene · pn: pn · ps: ps
  • Genes fisherge_mk_genes · dn: dn · ds: ds · gene: gene · pn: pn · ps: ps
  • Degenerate all nage_mk_guide · dn: dn · ds: ds · pn: pn · ps: ps
  • Degenerate infge_mk_guide · dn: dn · ds: ds · pn: pn · ps: ps

In the guides

Tests from the statistics guide this method runs

Where it sits in the decision guides

  • Two independent proportions · Statistics Guide · E — Compare proportions / frequencies

What you need

Polymorphic nonsynonymous (P_N)numeric · 1 column
Protein-changing sites that vary within the species; one row per gene.
Polymorphic synonymous (P_S)numeric · 1 column
Silent sites that vary within the species.
Fixed nonsynonymous (D_N)numeric · 1 column
Protein-changing differences fixed between the species.
Fixed synonymous (D_S)numeric · 1 column
Silent differences fixed between the species.
Gene (optional)categorical · 0–1 column
Labels the rows when there are several genes; each gets its own test.

Choices you make

hypothesis

Testdefault fisher

Fisher's exact test is valid for small counts; G and χ² need expected counts of about 5.

  • Fisher's exact test(default) — Conditions on the margins; the usual choice for MK tables.
  • G-test — Likelihood-ratio test on 1 df, as in McDonald & Kreitman (1991).
  • Pearson χ² — Without continuity correction, on 1 df.

statistics

Confidence leveldefault 0.95

For the conditional odds ratio (the neutrality index's exact interval).

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • Expected counts ≥ 5 (G and χ²)

    The approximate tests need well-filled cells; Fisher's test doesn't.

    • If violated → Fisher's exact test — Conditioning on the margins removes the need for large expected counts.
  • Synonymous sites are neutral

    The silent class is the neutral yardstick; codon bias breaks that.

  • Few slightly deleterious polymorphisms

    They inflate P_N, pull NI up and α down; excluding rare variants is a common remedy.

  • Correct orthology and site classes

    Polymorphic vs fixed and synonymous vs nonsynonymous calls must be right, with one outgroup.

What it reports

  • Tests: Same nonsynonymous/synonymous ratio for polymorphism and divergence
pn
Nonsynonymous and synonymous changes counted as polymorphic within a species (P) or fixed between species (D).
ps
Nonsynonymous and synonymous changes counted as polymorphic within a species (P) or fixed between species (D).
dn
Nonsynonymous and synonymous changes counted as polymorphic within a species (P) or fixed between species (D).
ds
Nonsynonymous and synonymous changes counted as polymorphic within a species (P) or fixed between species (D).
n_genes
Nonsynonymous and synonymous changes counted as polymorphic within a species (P) or fixed between species (D).
p
Nonsynonymous and synonymous changes counted as polymorphic within a species (P) or fixed between species (D).
p_fisher
Nonsynonymous and synonymous changes counted as polymorphic within a species (P) or fixed between species (D).
p_fisher_less
Nonsynonymous and synonymous changes counted as polymorphic within a species (P) or fixed between species (D).
p_fisher_greater
Nonsynonymous and synonymous changes counted as polymorphic within a species (P) or fixed between species (D).
or_cmle
NI = (P_N/P_S)/(D_N/D_S). Above 1 points to slightly deleterious polymorphism, below 1 to adaptive change; α = 1 − NI.
or_low
NI = (P_N/P_S)/(D_N/D_S). Above 1 points to slightly deleterious polymorphism, below 1 to adaptive change; α = 1 − NI.
or_high
NI = (P_N/P_S)/(D_N/D_S). Above 1 points to slightly deleterious polymorphism, below 1 to adaptive change; α = 1 − NI.
or_reference
(D_N·P_S)/(P_N·D_S), the same table read the other way; it is the reciprocal of the neutrality-index odds ratio.
or_reference_cmle
(D_N·P_S)/(P_N·D_S), the same table read the other way; it is the reciprocal of the neutrality-index odds ratio.
chi2
Nonsynonymous and synonymous changes counted as polymorphic within a species (P) or fixed between species (D).
p_chisq
Nonsynonymous and synonymous changes counted as polymorphic within a species (P) or fixed between species (D).
g2
Nonsynonymous and synonymous changes counted as polymorphic within a species (P) or fixed between species (D).
p_g
Nonsynonymous and synonymous changes counted as polymorphic within a species (P) or fixed between species (D).
min_expected
Nonsynonymous and synonymous changes counted as polymorphic within a species (P) or fixed between species (D).
ni
NI = (P_N/P_S)/(D_N/D_S). Above 1 points to slightly deleterious polymorphism, below 1 to adaptive change; α = 1 − NI.
alpha
NI = (P_N/P_S)/(D_N/D_S). Above 1 points to slightly deleterious polymorphism, below 1 to adaptive change; α = 1 − NI.
alpha_tg
NI = (P_N/P_S)/(D_N/D_S). Above 1 points to slightly deleterious polymorphism, below 1 to adaptive change; α = 1 − NI.
dos
D_N/(D_N + D_S) − P_N/(P_N + P_S). Positive values point to adaptive evolution, negative to slightly deleterious polymorphism.
test
Nonsynonymous and synonymous changes counted as polymorphic within a species (P) or fixed between species (D).
gene_p
Nonsynonymous and synonymous changes counted as polymorphic within a species (P) or fixed between species (D).
gene_ni
NI = (P_N/P_S)/(D_N/D_S). Above 1 points to slightly deleterious polymorphism, below 1 to adaptive change; α = 1 − NI.
gene_dos
D_N/(D_N + D_S) − P_N/(P_N + P_S). Positive values point to adaptive evolution, negative to slightly deleterious polymorphism.

Python and R

Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.

Default traps between the two languages

  • The conditional odds ratio and its exact interval are solved by bisection to machine precision; R's fisher.test stops uniroot at about 1e-4, so its printed estimate and limits differ in the fifth digit (1.98444 vs 1.98447 on the guide's table).
Python

The exact script CodeSplash ran for example “Guide fisher” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# McDonald–Kreitman test
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method genetics.mk 1.1.1 · spec 83168d3002026461
# Dataset: ge_mk_guide (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import math

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.stats import genetics as gen  # McDonald–Kreitman tables, Fisher with conditional OR (twins of cs_gen_*)

# %% Data (no rows dropped here: genotype no-calls and missing values are handled by the analysis)
df = pd.read_parquet("tests/parity/fixtures/ge_mk_guide.parquet", columns=["pn", "ps", "dn", "ds"])
n_input = len(df)
warnings = []
research_note = "Research use only: not for clinical or diagnostic decisions. Genotypes are personal data."

# %% Counts
cols = ["pn", "ps", "dn", "ds"]
gene_col = None
ok = df[cols].notna().all(axis=1).to_numpy()
if (~ok).sum():
    warnings.append(f"{int((~ok).sum())} rows had a missing count and were left out.")
df = df[ok].reset_index(drop=True)
if not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, cols)  # infinite values stop the run (registry/errors.yaml)
genes = [str(v) for v in df[gene_col]] if gene_col else [f"row {i + 1}" for i in range(len(df))]
test = "fisher"
conf = float(0.95)
r = gen.mk_test(*(df[c].to_numpy(dtype=float) for c in cols), conf)
p = {"fisher": r["p_fisher"], "g": r["p_g"], "chisq": r["p_chisq"]}[test]
label = {"fisher": "Fisher's exact test", "g": "G-test", "chisq": "Pearson χ² test"}[test]
if len(df) > 1:
    warnings.append(f"{len(df)} genes: the summed table pools them, which can bias α when genes differ; α across genes (α_TG) weights each gene by its own counts.")

# %% Assumptions
me = r["min_expected"]
if test == "fisher":
    e_status, e_detail = "info", f"Fisher's test conditions on the margins; the smallest expected count is {me:.2f}."
elif me < 5:
    e_status, e_detail = "warn", f"The smallest expected count is {me:.2f}, below 5: prefer Fisher's exact test."
else:
    e_status, e_detail = "pass", f"Every expected count is at least 5 (smallest {me:.2f})."
assumptions = [
    {"key": "expected_counts", "label": "Expected counts ≥ 5 (G and χ²)", "status": e_status, "detail": e_detail},
    {"key": "neutral_synonymous", "label": "Synonymous sites are neutral", "status": "info", "detail": "Not checkable from counts: strong codon bias would break the yardstick."},
    {"key": "deleterious", "label": "Few slightly deleterious polymorphisms", "status": "warn" if r["ni"] > 1 else "info",
     "detail": "NI above 1: an excess of protein-changing polymorphism, the signature of slightly deleterious variants that bias α downwards." if r["ni"] > 1
     else "Excluding rare polymorphisms (for example below 5–15% frequency) reduces their bias."},
    {"key": "classification", "label": "Correct orthology and site classes", "status": "info", "detail": "Assumed: one outgroup, polymorphic and fixed sites called correctly."},
]

# %% Result
summary = (f"P_N = {r['pn']:g}, P_S = {r['ps']:g}, D_N = {r['dn']:g}, D_S = {r['ds']:g}: NI = {r['ni']:.3f}, α = {r['alpha']:.3f}, "
           f"DoS = {r['dos']:.3f}; {label}, {cs.fmt_p(p)}.")
apa = f"McDonald–Kreitman test, P_N = {r['pn']:g}, P_S = {r['ps']:g}, D_N = {r['dn']:g}, D_S = {r['ds']:g}, {cs.fmt_p(p)}, NI = {cs.fmt_num(r['ni'])}"
table = [{"class": "Polymorphic", "nonsynonymous": r["pn"], "synonymous": r["ps"]}, {"class": "Fixed", "nonsynonymous": r["dn"], "synonymous": r["ds"]}]
gene_rows = [{"gene": genes[x["i"]], **{k: x[k] for k in ("pn", "ps", "dn", "ds", "p_fisher", "p_g", "ni", "alpha", "dos")}} for x in r["genes"]]
tests = [{"test": "Fisher's exact (two-sided)", "statistic": None, "p": r["p_fisher"]},
         {"test": "G-test", "statistic": r["g2"], "p": r["p_g"]},
         {"test": "Pearson χ²", "statistic": r["chi2"], "p": r["p_chisq"]}]
notes = [research_note,
         "NI = (P_N/P_S)/(D_N/D_S): above 1 points to slightly deleterious polymorphism, below 1 to adaptive substitution; α = 1 − NI.",
         f"Conditional odds ratio {r['or_cmle']:.3f} ({conf:.0%} exact CI {r['or_low']:.3f} to {r['or_high']:.3f}) estimates NI from the table.",
         "Odds-ratio direction: the headline odds ratio is polymorphic over fixed (NI orientation, (P_N/P_S)/(D_N/D_S)). The reference's MK odds ratio is fixed over polymorphic, its reciprocal: reported as or_reference (sample) and or_reference_cmle (conditional). One-sided Fisher p: 'less' tests NI < 1 (adaptive substitution), 'greater' tests NI > 1."]
values = {k: r[k] for k in ("pn", "ps", "dn", "ds", "n_genes", "p_fisher", "p_fisher_less", "p_fisher_greater", "or_cmle", "or_low", "or_high",
                            "chi2", "p_chisq", "g2", "p_g", "min_expected", "ni", "alpha", "alpha_tg", "dos")}
def _inv(v):
    """Reciprocal with 0 ↔ ∞ (the reference's fixed-over-polymorphic orientation)."""
    return math.inf if v == 0 else (0.0 if math.isinf(v) else 1.0 / v)


values.update({"or_reference": _inv(r["ni"]), "or_reference_cmle": _inv(r["or_cmle"])})
values.update({"p": p, "test": test, "gene_p": [x["p_fisher"] for x in r["genes"]], "gene_ni": [x["ni"] for x in r["genes"]],
               "gene_dos": [x["dos"] for x in r["genes"]]})
cs.publish({
    "method": "genetics.mk",
    "methodVersion": "1.1.1",
    "title": "McDonald–Kreitman test",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": int(r["pn"] + r["ps"] + r["dn"] + r["ds"]),
    "summary": summary,
    "apa": apa,
    "statistics": [
        {"key": "ni", "label": "Neutrality index NI", "value": r["ni"]},
        {"key": "alpha", "label": "α (adaptive substitutions)", "value": r["alpha"]},
        {"key": "dos", "label": "Direction of selection DoS", "value": r["dos"]},
        {"key": "p", "label": f"p ({label})", "value": p, "format": "p"},
    ],
    "tables": [
        {"key": "table", "title": "McDonald–Kreitman table",
         "columns": [{"key": "class", "label": "", "type": "string"}, {"key": "nonsynonymous", "label": "Nonsynonymous", "type": "integer"},
                     {"key": "synonymous", "label": "Synonymous", "type": "integer"}],
         "rows": table},
        {"key": "tests", "title": "Tests of the summed table",
         "columns": [{"key": "test", "label": "Test", "type": "string"}, {"key": "statistic", "label": "Statistic", "type": "number"}, {"key": "p", "label": "p", "type": "p"}],
         "rows": tests},
    ] + ([{"key": "genes", "title": "Each gene",
           "columns": [{"key": "gene", "label": "Gene", "type": "string"}, {"key": "pn", "label": "P_N", "type": "integer"}, {"key": "ps", "label": "P_S", "type": "integer"},
                       {"key": "dn", "label": "D_N", "type": "integer"}, {"key": "ds", "label": "D_S", "type": "integer"}, {"key": "p_fisher", "label": "p (Fisher)", "type": "p"},
                       {"key": "p_g", "label": "p (G)", "type": "p"}, {"key": "ni", "label": "NI", "type": "number"}, {"key": "alpha", "label": "α", "type": "number"},
                       {"key": "dos", "label": "DoS", "type": "number"}],
           "rows": gene_rows}] if len(gene_rows) > 1 else []),
    "effectSizes": [{"key": "or_cmle", "label": "Neutrality index (conditional odds ratio)", "value": r["or_cmle"], "ciLow": r["or_low"],
                     "ciHigh": r["or_high"], "ciLevel": conf, "method": "Conditional MLE with exact interval"}],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": notes,
    "charts": [],
    "values": values,
})
R

The exact script CodeSplash ran for example “Guide fisher” · R version 4.5.1 (2025-06-13)

# McDonald–Kreitman test
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method genetics.mk 1.1.1 · spec 83168d3002026461
# Dataset: ge_mk_guide (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_gen_mk_test, cs_gen_fisher_2x2 (twins of codesplash.stats.genetics)

# %% Data (no rows dropped here: genotype no-calls and missing values are handled by the analysis)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ge_mk_guide.parquet", col_select = c("pn", "ps", "dn", "ds")))
n_input <- nrow(df)
warnings <- list()
research_note <- "Research use only: not for clinical or diagnostic decisions. Genotypes are personal data."

# %% Counts
cols <- c("pn", "ps", "dn", "ds")
gene_col <- NULL
ok <- stats::complete.cases(df[cols])
if (sum(!ok) > 0) warnings <- c(warnings, sprintf("%d rows had a missing count and were left out.", sum(!ok)))
df <- df[ok, , drop = FALSE]
if (nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, cols)  # infinite values stop the run (registry/errors.yaml)
genes <- if (!is.null(gene_col)) as.character(df[[gene_col]]) else sprintf("row %d", seq_len(nrow(df)))
test <- "fisher"
conf <- 0.95
r <- cs_gen_mk_test(df[[cols[1]]], df[[cols[2]]], df[[cols[3]]], df[[cols[4]]], conf)
p <- switch(test, fisher = r$p_fisher, g = r$p_g, chisq = r$p_chisq)
label <- switch(test, fisher = "Fisher's exact test", g = "G-test", chisq = "Pearson χ² test")
if (nrow(df) > 1) {
  warnings <- c(warnings, sprintf("%d genes: the summed table pools them, which can bias α when genes differ; α across genes (α_TG) weights each gene by its own counts.", nrow(df)))
}

# %% Assumptions
me <- r$min_expected
if (test == "fisher") {
  e_status <- "info"
  e_detail <- sprintf("Fisher's test conditions on the margins; the smallest expected count is %.2f.", me)
} else if (me < 5) {
  e_status <- "warn"
  e_detail <- sprintf("The smallest expected count is %.2f, below 5: prefer Fisher's exact test.", me)
} else {
  e_status <- "pass"
  e_detail <- sprintf("Every expected count is at least 5 (smallest %.2f).", me)
}
ni_high <- !is.na(r$ni) && r$ni > 1
assumptions <- list(
  list(key = "expected_counts", label = "Expected counts ≥ 5 (G and χ²)", status = e_status, detail = e_detail),
  list(key = "neutral_synonymous", label = "Synonymous sites are neutral", status = "info", detail = "Not checkable from counts: strong codon bias would break the yardstick."),
  list(key = "deleterious", label = "Few slightly deleterious polymorphisms", status = if (ni_high) "warn" else "info",
       detail = if (ni_high) "NI above 1: an excess of protein-changing polymorphism, the signature of slightly deleterious variants that bias α downwards." else
         "Excluding rare polymorphisms (for example below 5–15% frequency) reduces their bias."),
  list(key = "classification", label = "Correct orthology and site classes", status = "info", detail = "Assumed: one outgroup, polymorphic and fixed sites called correctly.")
)

# %% Result
summary <- sprintf("P_N = %s, P_S = %s, D_N = %s, D_S = %s: NI = %.3f, α = %.3f, DoS = %.3f; %s, %s.",
                   format(r$pn), format(r$ps), format(r$dn), format(r$ds), r$ni, r$alpha, r$dos, label, cs_fmt_p(p))
apa <- sprintf("McDonald–Kreitman test, P_N = %s, P_S = %s, D_N = %s, D_S = %s, %s, NI = %s",
               format(r$pn), format(r$ps), format(r$dn), format(r$ds), cs_fmt_p(p), cs_fmt_num(r$ni))
table <- list(list(class = "Polymorphic", nonsynonymous = r$pn, synonymous = r$ps), list(class = "Fixed", nonsynonymous = r$dn, synonymous = r$ds))
gene_rows <- lapply(r$genes, function(x) c(list(gene = genes[x$i + 1]), x[c("pn", "ps", "dn", "ds", "p_fisher", "p_g", "ni", "alpha", "dos")]))
tests <- list(list(test = "Fisher's exact (two-sided)", statistic = NA, p = r$p_fisher),
              list(test = "G-test", statistic = r$g2, p = r$p_g),
              list(test = "Pearson χ²", statistic = r$chi2, p = r$p_chisq))
notes <- list(research_note,
              "NI = (P_N/P_S)/(D_N/D_S): above 1 points to slightly deleterious polymorphism, below 1 to adaptive substitution; α = 1 − NI.",
              sprintf("Conditional odds ratio %.3f (%.0f%% exact CI %.3f to %.3f) estimates NI from the table.", r$or_cmle, 100 * conf, r$or_low, r$or_high),
              "Odds-ratio direction: the headline odds ratio is polymorphic over fixed (NI orientation, (P_N/P_S)/(D_N/D_S)). The reference's MK odds ratio is fixed over polymorphic, its reciprocal: reported as or_reference (sample) and or_reference_cmle (conditional). One-sided Fisher p: 'less' tests NI < 1 (adaptive substitution), 'greater' tests NI > 1.")
result_values <- c(r[c("pn", "ps", "dn", "ds", "n_genes", "p_fisher", "p_fisher_less", "p_fisher_greater", "or_cmle", "or_low", "or_high",
                       "chi2", "p_chisq", "g2", "p_g", "min_expected", "ni", "alpha", "alpha_tg", "dos")],
                   list(or_reference = 1 / r$ni, or_reference_cmle = 1 / r$or_cmle),  # the reference's fixed-over-polymorphic orientation
                   list(p = p, test = test, gene_p = I(vapply(r$genes, function(x) x$p_fisher, numeric(1))),
                        gene_ni = I(vapply(r$genes, function(x) x$ni, numeric(1))), gene_dos = I(vapply(r$genes, function(x) x$dos, numeric(1)))))
tables <- list(
  list(key = "table", title = "McDonald–Kreitman table",
       columns = list(list(key = "class", label = "", type = "string"), list(key = "nonsynonymous", label = "Nonsynonymous", type = "integer"),
                      list(key = "synonymous", label = "Synonymous", type = "integer")),
       rows = table),
  list(key = "tests", title = "Tests of the summed table",
       columns = list(list(key = "test", label = "Test", type = "string"), list(key = "statistic", label = "Statistic", type = "number"), list(key = "p", label = "p", type = "p")),
       rows = tests)
)
if (length(gene_rows) > 1) {
  tables[[3]] <- list(key = "genes", title = "Each gene",
                      columns = list(list(key = "gene", label = "Gene", type = "string"), list(key = "pn", label = "P_N", type = "integer"), list(key = "ps", label = "P_S", type = "integer"),
                                     list(key = "dn", label = "D_N", type = "integer"), list(key = "ds", label = "D_S", type = "integer"), list(key = "p_fisher", label = "p (Fisher)", type = "p"),
                                     list(key = "p_g", label = "p (G)", type = "p"), list(key = "ni", label = "NI", type = "number"), list(key = "alpha", label = "α", type = "number"),
                                     list(key = "dos", label = "DoS", type = "number")),
                      rows = gene_rows)
}
cs_publish(list(
  method = "genetics.mk",
  methodVersion = "1.1.1",
  title = "McDonald–Kreitman test",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = r$pn + r$ps + r$dn + r$ds,
  summary = summary,
  apa = apa,
  statistics = list(
    list(key = "ni", label = "Neutrality index NI", value = r$ni),
    list(key = "alpha", label = "α (adaptive substitutions)", value = r$alpha),
    list(key = "dos", label = "Direction of selection DoS", value = r$dos),
    list(key = "p", label = sprintf("p (%s)", label), value = p, format = "p")
  ),
  tables = tables,
  effectSizes = list(list(key = "or_cmle", label = "Neutrality index (conditional odds ratio)", value = r$or_cmle, ciLow = r$or_low,
                          ciHigh = r$or_high, ciLevel = conf, method = "Conditional MLE with exact interval")),
  assumptions = assumptions,
  warnings = warnings,
  notes = notes,
  charts = list(),
  values = result_values
))

Sources

  • McDonald, J. H., & Kreitman, M. (1991). Adaptive protein evolution at the Adh locus in Drosophila. Nature, 351, 652–654.
  • Smith, N. G. C., & Eyre-Walker, A. (2002). Adaptive protein evolution in Drosophila. Nature, 415, 1022–1024.
  • Stoletzki, N., & Eyre-Walker, A. (2011). Estimation of the neutrality index. Molecular Biology and Evolution, 28, 63–70.
  • Murga-Moreno, J., Coronado-Zamora, M., Hervas, S., Casillas, S., & Barbadilla, A. (2019). iMKT: the integrative McDonald and Kreitman test. Nucleic Acids Research, 47, W283–W288.

From the CodeSplash method registry · genetics.mk v1.1.1.