Skip to content

EGenetics · genetics.ld

Linkage disequilibrium (D′, r²)

Which markers are inherited together, and how strongly?

Measures the association between alleles at pairs of markers. From unphased genotypes, haplotype frequencies are estimated by EM (Hill 1974), giving D, Lewontin's D′ and r²; the correlation of dosages (Rogers and Huff 2009) gives a quick r² that needs no phasing. Every pair of the chosen markers is measured, with distances when you give positions, for an LD heatmap or a decay plot. People without a call at either marker of a pair are left out of that pair. Research use only.

Experimental Python and R agree to 10 decimals Also called LD, linkage disequilibrium, D prime…

A real result

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

Linkage disequilibriumRecorded · Python and R agreeRecorded 2026-11-17 · 18 values compared
R

Linkage disequilibrium, 28 pairs, N = 300, mean r² = 0.31

Pairs
28
Mean r²
0.3123
Largest r²
0.7958
Pairs with r² ≥ 0.8
0

Assumptions

  • Random mating (EM) — EM haplotypes assume Hardy–Weinberg proportions; check them per marker in QC.
  • One population — Not checkable here: if people come from several populations, measure LD within each.
  • Enough people per pair — Between 283 and 295 people per pair.

Every pair

Marker AMarker BDistance (bp)PeopleDD′r²Dosage r²
v01v02—2890.03900.18740.02480.0238
v01v03—2830.01660.08290.00450.0049
v01v04—2840.21540.90740.76130.7800
v01v05—287−0.2178−0.89650.78690.7860
v01v06—285−0.0388−0.18800.02450.0258
v01v07—2840.22040.93770.79580.7953
v01v08—287−0.2139−0.88710.74910.7559
v02v03—2910.00140.00613.324e-53.290e-5
v02v04—2920.03800.17480.02340.0230
v02v05—294−0.0490−0.23930.03930.0353
v02v06—293−0.2222−0.90030.79410.8014
v02v07—2910.05230.23790.04420.0383
v02v08—295−0.0406−0.18820.02660.0221
v03v04—2870.01110.05380.00200.0019
v03v05—288−0.0264−0.13410.01140.0102
v03v06—287−0.0009−0.00391.403e-51.293e-5
v03v07—2850.00180.00855.172e-55.030e-5
v03v08—290−0.0242−0.11800.00950.0081
v04v05—290−0.2136−0.90820.75300.7692
v04v06—289−0.0412−0.19250.02750.0290
v04v07—2870.21540.87560.75600.7621
v04v08—290−0.2111−0.86710.72620.7376
v05v06—2900.04770.23510.03720.0356
v05v07—288−0.2183−0.93770.78560.7722
v05v08—2920.21100.88690.73380.7249
v06v07—287−0.0473−0.21880.03620.0353
v06v08—2920.04060.19140.02670.0237
v07v08—289−0.2165−0.89580.76420.7554

Alleles counted

MarkerCounted alleleOther alleleFrequency
v01BA0.5621
v02BA0.4799
v03BA0.4521
v04BA0.5476
v05BA0.4291
v06BA0.5289
v07BA0.5445
v08BA0.4493
  • Research use only: not for clinical or diagnostic decisions. Genotypes are personal data.
  • D′ = 1 means no recombinant haplotype was seen, which also happens by chance with rare alleles; r² says how well one marker predicts the other.
  • Signs of D and D′ depend on which allele is counted at each marker (the second in code-point order).
Python

Linkage disequilibrium, 28 pairs, N = 300, mean r² = 0.31

Pairs
28
Mean r²
0.3123
Largest r²
0.7958
Pairs with r² ≥ 0.8
0

Assumptions

  • Random mating (EM) — EM haplotypes assume Hardy–Weinberg proportions; check them per marker in QC.
  • One population — Not checkable here: if people come from several populations, measure LD within each.
  • Enough people per pair — Between 283 and 295 people per pair.

Every pair

Marker AMarker BDistance (bp)PeopleDD′r²Dosage r²
v01v02—2890.03900.18740.02480.0238
v01v03—2830.01660.08290.00450.0049
v01v04—2840.21540.90740.76130.7800
v01v05—287−0.2178−0.89650.78690.7860
v01v06—285−0.0388−0.18800.02450.0258
v01v07—2840.22040.93770.79580.7953
v01v08—287−0.2139−0.88710.74910.7559
v02v03—2910.00140.00613.324e-53.290e-5
v02v04—2920.03800.17480.02340.0230
v02v05—294−0.0490−0.23930.03930.0353
v02v06—293−0.2222−0.90030.79410.8014
v02v07—2910.05230.23790.04420.0383
v02v08—295−0.0406−0.18820.02660.0221
v03v04—2870.01110.05380.00200.0019
v03v05—288−0.0264−0.13410.01140.0102
v03v06—287−0.0009−0.00391.403e-51.293e-5
v03v07—2850.00180.00855.172e-55.030e-5
v03v08—290−0.0242−0.11800.00950.0081
v04v05—290−0.2136−0.90820.75300.7692
v04v06—289−0.0412−0.19250.02750.0290
v04v07—2870.21540.87560.75600.7621
v04v08—290−0.2111−0.86710.72620.7376
v05v06—2900.04770.23510.03720.0356
v05v07—288−0.2183−0.93770.78560.7722
v05v08—2920.21100.88690.73380.7249
v06v07—287−0.0473−0.21880.03620.0353
v06v08—2920.04060.19140.02670.0237
v07v08—289−0.2165−0.89580.76420.7554

Alleles counted

MarkerCounted alleleOther alleleFrequency
v01BA0.5621
v02BA0.4799
v03BA0.4521
v04BA0.5476
v05BA0.4291
v06BA0.5289
v07BA0.5445
v08BA0.4493
  • Research use only: not for clinical or diagnostic decisions. Genotypes are personal data.
  • D′ = 1 means no recombinant haplotype was seen, which also happens by chance with rare alleles; r² says how well one marker predicts the other.
  • Signs of D and D′ depend on which allele is counted at each marker (the second in code-point order).

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

Worked examples in the app

  • Block r2ge_people · variants: v01, v02, v03, v04, v05, v06, v07, v08
  • Block dprime positionsge_people · variants: v01, v02, v03, v04, v05, v06, v07, v08
  • Pair vcfge_people · variants: gt1, gt2
  • Pair dosagege_people · variants: v01, v04
  • Degenerate infge_people · variants: v01, v02, v03, v04, v05, v06, v07, v08
  • Degenerate tiesge_people · variants: v01, v02, v03, v04, v05, v06, v07, v08

In the guides

Where it sits in the decision guides

  • Categorical–categorical: χ², Fisher, Cramér's V · Statistics Guide · C — Test association

What you need

Markersnumeric / categorical · 2–200 columns
One column per marker, one row per person: doses 0/1/2, VCF calls (0/1, 1|1, ./.) or two alleles.

Choices you make

statistics

Summary measuredefault r2

Which measure the summary, threshold count and heatmap use; every measure is reported for each pair.

  • r² (EM haplotypes)(default) — Squared correlation of alleles on haplotypes; predicts how well one marker tags the other.
  • |D′| (EM haplotypes) — D scaled by its largest possible value; 1 means no recombinant haplotype was seen.
  • r² of dosages — Correlation of genotype doses (Rogers & Huff 2009); no phasing, close to r² near equilibrium.
Strong LD thresholddefault 0.8

Pairs at or above it are counted as strong LD (r² ≥ 0.8 is the usual tagging rule).

options

Marker positions (bp)default

Optional, one per marker in the same order: adds the distance of each pair for an LD decay plot.

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.

  • Random mating (EM)

    EM haplotype estimation assumes Hardy–Weinberg proportions; dosage r² doesn't.

  • One population

    Mixing populations with different allele frequencies creates LD between unlinked markers.

  • Enough people per pair

    D′ is biased upwards in small samples and for rare alleles; r² is more stable.

What it reports

n
Alleles at two markers inherited together more often than chance. D′ scales D by its largest possible value; r² is the squared correlation.
n_variants
Alleles at two markers inherited together more often than chance. D′ scales D by its largest possible value; r² is the squared correlation.
n_pairs
Alleles at two markers inherited together more often than chance. D′ scales D by its largest possible value; r² is the squared correlation.
measure
Alleles at two markers inherited together more often than chance. D′ scales D by its largest possible value; r² is the squared correlation.
measure_label
Alleles at two markers inherited together more often than chance. D′ scales D by its largest possible value; r² is the squared correlation.
mean_measure
Alleles at two markers inherited together more often than chance. D′ scales D by its largest possible value; r² is the squared correlation.
max_measure
Alleles at two markers inherited together more often than chance. D′ scales D by its largest possible value; r² is the squared correlation.
n_strong
Alleles at two markers inherited together more often than chance. D′ scales D by its largest possible value; r² is the squared correlation.
threshold
Alleles at two markers inherited together more often than chance. D′ scales D by its largest possible value; r² is the squared correlation.
d
Alleles at two markers inherited together more often than chance. D′ scales D by its largest possible value; r² is the squared correlation.
dprime
Alleles at two markers inherited together more often than chance. D′ scales D by its largest possible value; r² is the squared correlation.
r2
Alleles at two markers inherited together more often than chance. D′ scales D by its largest possible value; r² is the squared correlation.
r2_dosage
Alleles at two markers inherited together more often than chance. D′ scales D by its largest possible value; r² is the squared correlation.
pair_r2
Alleles at two markers inherited together more often than chance. D′ scales D by its largest possible value; r² is the squared correlation.
pair_dprime
Alleles at two markers inherited together more often than chance. D′ scales D by its largest possible value; r² is the squared correlation.
pair_r2_dosage
Alleles at two markers inherited together more often than chance. D′ scales D by its largest possible value; r² is the squared correlation.
pair_n
Alleles at two markers inherited together more often than chance. D′ scales D by its largest possible value; r² is the squared correlation.
pair_distance
Alleles at two markers inherited together more often than chance. D′ scales D by its largest possible value; r² is the squared correlation.

Python and R

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

Default traps between the two languages

  • EM runs from the same start to the same tolerance (10⁻¹² on haplotype frequencies) in both engines, so D, D′ and r² agree to rounding.
Python

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

# Linkage disequilibrium (D′, r²)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method genetics.ld 1.0.1 · spec 5b5f799678f8fb88
# Dataset: ge_people (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  # EM haplotypes, D, D′, r², dosage r (twins of cs_gen_ld_*)

# %% Data (no rows dropped here: genotype no-calls and missing values are handled by the analysis)
df = pd.read_parquet("tests/parity/fixtures/ge_people.parquet", columns=["v01", "v02", "v03", "v04", "v05", "v06", "v07", "v08"])
n_input = len(df)
warnings = []
research_note = "Research use only: not for clinical or diagnostic decisions. Genotypes are personal data."

# %% Markers
variants = ["v01", "v02", "v03", "v04", "v05", "v06", "v07", "v08"]
measure = "r2"
threshold = float(0.8)
positions = [] or None
if positions is not None and len(positions) != len(variants):
    raise ValueError(f"Give one position per marker: {len(variants)} markers but {len(positions)} positions.")
g, counted, other = gen.dose_matrix({v: df[v].to_numpy() for v in variants})
n = int(np.sum(np.any(~np.isnan(g), axis=1)))

# %% Pairs
pairs = gen.ld_matrix(g, variants, positions)
key = {"r2": "r2", "dprime": "dprime", "r2_dosage": "r2_dosage"}[measure]
vals = np.array([abs(x[key]) for x in pairs], dtype=float)
ok = ~np.isnan(vals)
mean_m = float(np.mean(vals[ok])) if ok.any() else math.nan
max_m = float(np.max(vals[ok])) if ok.any() else math.nan
n_strong = int(np.sum(vals[ok] >= threshold))
label = {"r2": "r²", "dprime": "|D′|", "r2_dosage": "dosage r²"}[measure]
n_undefined = int(np.sum(~ok))
if n_undefined:
    warnings.append(f"{n_undefined} pairs have no LD measure because a marker is monomorphic in the people called at both.")
low_n = [f"{x['a']}–{x['b']}" for x in pairs if x["n"] < 50]
if low_n:
    warnings.append(f"{len(low_n)} pairs rest on fewer than 50 people with calls at both markers; D′ is biased upwards there.")

# %% Assumptions
assumptions = [
    {"key": "hwe", "label": "Random mating (EM)", "status": "info", "detail": "EM haplotypes assume Hardy–Weinberg proportions; check them per marker in QC."},
    {"key": "one_population", "label": "One population", "status": "info", "detail": "Not checkable here: if people come from several populations, measure LD within each."},
    {"key": "sample_size", "label": "Enough people per pair", "status": "warn" if low_n else "pass",
     "detail": f"Between {int(min(x['n'] for x in pairs))} and {int(max(x['n'] for x in pairs))} people per pair."},
]

# %% Result
first = pairs[0]
summary = (f"LD across {len(pairs)} pairs of {len(variants)} markers ({n} people): mean {label} {mean_m:.3f}, largest {max_m:.3f}; "
           f"{n_strong} pairs at or above {threshold:g}.")
apa = f"Linkage disequilibrium, {len(pairs)} pairs, N = {n}, mean {label} = {cs.fmt_num(mean_m)}"
rows = [{"a": x["a"], "b": x["b"], "distance": x["distance"], "n": x["n"], "d": x["d"], "dprime": x["dprime"], "r2": x["r2"],
         "r2_dosage": x["r2_dosage"]} for x in pairs]
alleles = [{"marker": v, "counted": counted[i], "other": other[i], "freq": float(np.nanmean(g[:, i]) / 2)} for i, v in enumerate(variants)]
notes = [research_note,
         "D′ = 1 means no recombinant haplotype was seen, which also happens by chance with rare alleles; r² says how well one marker predicts the other.",
         "Signs of D and D′ depend on which allele is counted at each marker (the second in code-point order)."]
charts = []
if positions is not None:
    charts.append(cs.chart("decay", "scatter", f"{label} against distance", {
        "x": cs.col("Distance (bp)", [x["distance"] for x in pairs], "numeric"), "y": cs.col(label, vals.tolist(), "numeric")}, controls={"fit": "loess"}))
values = {
    "n": n, "n_variants": len(variants), "n_pairs": len(pairs), "measure": measure, "measure_label": label, "mean_measure": mean_m,
    "max_measure": max_m, "n_strong": n_strong, "threshold": threshold, "d": first["d"], "dprime": first["dprime"], "r2": first["r2"],
    "r2_dosage": first["r2_dosage"], "pair_r2": [x["r2"] for x in pairs], "pair_dprime": [x["dprime"] for x in pairs],
    "pair_r2_dosage": [x["r2_dosage"] for x in pairs], "pair_n": [x["n"] for x in pairs], "pair_distance": [x["distance"] for x in pairs],
}
cs.publish({
    "method": "genetics.ld",
    "methodVersion": "1.0.1",
    "title": "Linkage disequilibrium",
    "engine": cs.engine_info("pandas", "numpy"),
    "n": n,
    "summary": summary,
    "apa": apa,
    "statistics": [
        {"key": "n_pairs", "label": "Pairs", "value": len(pairs)},
        {"key": "mean_measure", "label": f"Mean {label}", "value": mean_m},
        {"key": "max_measure", "label": f"Largest {label}", "value": max_m},
        {"key": "n_strong", "label": f"Pairs with {label} ≥ {threshold:g}", "value": n_strong},
    ],
    "tables": [
        {"key": "pairs", "title": "Every pair",
         "columns": [{"key": "a", "label": "Marker A", "type": "string"}, {"key": "b", "label": "Marker B", "type": "string"},
                     {"key": "distance", "label": "Distance (bp)", "type": "number"}, {"key": "n", "label": "People", "type": "integer"},
                     {"key": "d", "label": "D", "type": "number"}, {"key": "dprime", "label": "D′", "type": "number"},
                     {"key": "r2", "label": "r²", "type": "number"}, {"key": "r2_dosage", "label": "Dosage r²", "type": "number"}],
         "rows": rows},
        {"key": "alleles", "title": "Alleles counted",
         "columns": [{"key": "marker", "label": "Marker", "type": "string"}, {"key": "counted", "label": "Counted allele", "type": "string"},
                     {"key": "other", "label": "Other allele", "type": "string"}, {"key": "freq", "label": "Frequency", "type": "number"}],
         "rows": alleles},
    ],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": notes,
    "charts": charts,
    "values": values,
})
R

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

# Linkage disequilibrium (D′, r²)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method genetics.ld 1.0.1 · spec 5b5f799678f8fb88
# Dataset: ge_people (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_ld_matrix (EM haplotypes, D, D', r2, dosage r; twin 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_people.parquet", col_select = c("v01", "v02", "v03", "v04", "v05", "v06", "v07", "v08")))
n_input <- nrow(df)
warnings <- list()
research_note <- "Research use only: not for clinical or diagnostic decisions. Genotypes are personal data."

# %% Markers
variants <- c("v01", "v02", "v03", "v04", "v05", "v06", "v07", "v08")
measure <- "r2"
threshold <- 0.8
positions <- c()
if (!length(positions)) positions <- NULL
if (!is.null(positions) && length(positions) != length(variants)) {
  stop(sprintf("Give one position per marker: %d markers but %d positions.", length(variants), length(positions)), call. = FALSE)
}
dm <- cs_gen_dose_matrix(df[variants])
g <- dm$g
n <- sum(rowSums(!is.na(g)) > 0)

# %% Pairs
pairs <- cs_gen_ld_matrix(g, variants, positions)
key <- measure
vals <- vapply(pairs, function(x) abs(x[[key]]), numeric(1))
ok <- !is.na(vals)
mean_m <- if (any(ok)) mean(vals[ok]) else NaN
max_m <- if (any(ok)) max(vals[ok]) else NaN
n_strong <- sum(vals[ok] >= threshold)
label <- switch(measure, r2 = "r²", dprime = "|D′|", r2_dosage = "dosage r²")
n_undefined <- sum(!ok)
if (n_undefined > 0) warnings <- c(warnings, sprintf("%d pairs have no LD measure because a marker is monomorphic in the people called at both.", n_undefined))
pair_n <- vapply(pairs, function(x) as.numeric(x$n), numeric(1))
if (any(pair_n < 50)) warnings <- c(warnings, sprintf("%d pairs rest on fewer than 50 people with calls at both markers; D′ is biased upwards there.", sum(pair_n < 50)))

# %% Assumptions
assumptions <- list(
  list(key = "hwe", label = "Random mating (EM)", status = "info", detail = "EM haplotypes assume Hardy–Weinberg proportions; check them per marker in QC."),
  list(key = "one_population", label = "One population", status = "info", detail = "Not checkable here: if people come from several populations, measure LD within each."),
  list(key = "sample_size", label = "Enough people per pair", status = if (any(pair_n < 50)) "warn" else "pass",
       detail = sprintf("Between %d and %d people per pair.", as.integer(min(pair_n)), as.integer(max(pair_n))))
)

# %% Result
first <- pairs[[1]]
summary <- sprintf("LD across %d pairs of %d markers (%d people): mean %s %.3f, largest %.3f; %d pairs at or above %s.",
                   length(pairs), length(variants), n, label, mean_m, max_m, n_strong, format(threshold))
apa <- sprintf("Linkage disequilibrium, %d pairs, N = %d, mean %s = %s", length(pairs), n, label, cs_fmt_num(mean_m))
rows <- lapply(pairs, function(x) x[c("a", "b", "distance", "n", "d", "dprime", "r2", "r2_dosage")])
alleles <- lapply(seq_along(variants), function(i) list(marker = variants[i], counted = dm$counted[i], other = dm$other[i], freq = mean(g[, i], na.rm = TRUE) / 2))
notes <- list(research_note,
              "D′ = 1 means no recombinant haplotype was seen, which also happens by chance with rare alleles; r² says how well one marker predicts the other.",
              "Signs of D and D′ depend on which allele is counted at each marker (the second in code-point order).")
pick <- function(k) vapply(pairs, function(x) as.numeric(x[[k]]), numeric(1))
charts <- list()
if (!is.null(positions)) {
  charts[[1]] <- cs_chart("decay", "scatter", sprintf("%s against distance", label),
                          list(x = cs_col("Distance (bp)", pick("distance"), "numeric"), y = cs_col(label, vals, "numeric")), controls = list(fit = "loess"))
}
result_values <- list(
  n = n, n_variants = length(variants), n_pairs = length(pairs), measure = measure, measure_label = label, mean_measure = mean_m,
  max_measure = max_m, n_strong = n_strong, threshold = threshold, d = first$d, dprime = first$dprime, r2 = first$r2,
  r2_dosage = first$r2_dosage, pair_r2 = I(pick("r2")), pair_dprime = I(pick("dprime")), pair_r2_dosage = I(pick("r2_dosage")),
  pair_n = I(pair_n), pair_distance = I(pick("distance"))
)
cs_publish(list(
  method = "genetics.ld",
  methodVersion = "1.0.1",
  title = "Linkage disequilibrium",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = summary,
  apa = apa,
  statistics = list(
    list(key = "n_pairs", label = "Pairs", value = length(pairs)),
    list(key = "mean_measure", label = sprintf("Mean %s", label), value = mean_m),
    list(key = "max_measure", label = sprintf("Largest %s", label), value = max_m),
    list(key = "n_strong", label = sprintf("Pairs with %s ≥ %s", label, format(threshold)), value = n_strong)
  ),
  tables = list(
    list(key = "pairs", title = "Every pair",
         columns = list(list(key = "a", label = "Marker A", type = "string"), list(key = "b", label = "Marker B", type = "string"),
                        list(key = "distance", label = "Distance (bp)", type = "number"), list(key = "n", label = "People", type = "integer"),
                        list(key = "d", label = "D", type = "number"), list(key = "dprime", label = "D′", type = "number"),
                        list(key = "r2", label = "r²", type = "number"), list(key = "r2_dosage", label = "Dosage r²", type = "number")),
         rows = rows),
    list(key = "alleles", title = "Alleles counted",
         columns = list(list(key = "marker", label = "Marker", type = "string"), list(key = "counted", label = "Counted allele", type = "string"),
                        list(key = "other", label = "Other allele", type = "string"), list(key = "freq", label = "Frequency", type = "number")),
         rows = alleles)
  ),
  assumptions = assumptions,
  warnings = warnings,
  notes = notes,
  charts = charts,
  values = result_values
))

Sources

  • Hill, W. G. (1974). Estimation of linkage disequilibrium in randomly mating populations. Heredity, 33, 229–239.
  • Lewontin, R. C. (1964). The interaction of selection and linkage. I. General considerations; heterotic models. Genetics, 49, 49–67.
  • Excoffier, L., & Slatkin, M. (1995). Maximum-likelihood estimation of molecular haplotype frequencies in a diploid population. Molecular Biology and Evolution, 12, 921–927.
  • Rogers, A. R., & Huff, C. (2009). Linkage disequilibrium between loci with unknown phase. Genetics, 182, 839–844.

From the CodeSplash method registry · genetics.ld v1.0.1.