Mendelian Randomization
A genetic variant that raises LDL cholesterol is fixed at conception, before diet, smoking or illness can act on it. If the variant reaches the outcome only through LDL cholesterol, it works as a natural randomization, and a comparison of people by genotype estimates the causal effect of LDL cholesterol. This is Mendelian randomization: an instrumental variable analysis with genetic variants as the instruments.
This page computes the instrumental variable estimate from one variant and from many, with individual data and with summary statistics, and tests each method against a simulation in which the causal effect, the confounding and the pleiotropy are known.
Get the data
Section titled “Get the data”Download ldl_cimt_individuals.csv and ldl_cimt_summary.csv into your working directory. Both tables are invented. The individual table has 4,000 rows, one per person, and 17 columns. snp01 to snp15 count the copies of the LDL-raising allele at 15 independent variants (0, 1 or 2). ldl is LDL cholesterol in mmol/L and cimt is the carotid intima-media thickness in micrometers. The summary table has 60 rows, one per variant in each of four scenarios, and eight columns: scenario, variant, allele_frequency, beta_exposure and se_exposure from the regression of LDL cholesterol on the variant in 20,000 people, beta_outcome and se_outcome from the regression of CIMT on the variant in 50,000 other people, and direct_effect, the true direct effect of one allele on CIMT in the simulation.
The estimand is the change in CIMT caused by a 1 mmol/L increase in LDL cholesterol. In the simulation it is 40 micrometers per mmol/L for everyone. Each allele raises LDL cholesterol by 0.04 to 0.22 mmol/L. An unmeasured variable U raises LDL cholesterol by 0.45 mmol/L and CIMT by 45 micrometers per standard deviation, so U confounds the two. In the individual table and in the scenario valid, the variants act on CIMT only through LDL cholesterol. In the scenario balanced, each variant also has a direct effect on CIMT drawn from a normal distribution with mean 0 and standard deviation 2 micrometers per allele. In the scenario directional the mean of that distribution is 3. In the scenario minority, 4 of the 15 variants, chosen at random, have a direct effect drawn from that same distribution, and the other 11 are valid. The direct effects were drawn independently of the effects on LDL cholesterol.
library(ivreg)library(MendelianRandomization)library(ggplot2)
people <- read.csv("ldl_cimt_individuals.csv")summary_data <- read.csv("ldl_cimt_summary.csv")dir.create("outputs", showWarnings = FALSE)true_effect <- 40snps <- grep("^snp", names(people), value = TRUE)
#' Print an estimate with its standard error and normal 95% limits.#'#' @param label The text to print before the estimate.#' @param estimate The estimate in micrometers per mmol/L.#' @param se The standard error of the estimate.#' @return Invisibly, the estimate and its standard error.ReportEffect <- function(label, estimate, se) { z <- qnorm(0.975) cat(sprintf("%s: %.1f, SE %.2f, 95%% CI [%.1f, %.1f], truth %.0f\n", label, estimate, se, estimate - z * se, estimate + z * se, true_effect)) invisible(c(estimate = estimate, se = se))}
ols_fit <- lm(cimt ~ ldl, data = people)ReportEffect("Regression of CIMT on LDL", coef(ols_fit)[["ldl"]], coef(summary(ols_fit))["ldl", "Std. Error"])Regression of CIMT on LDL: 63.1, SE 1.88, 95% CI [59.4, 66.8], truth 40from pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport statsmodels.api as smimport statsmodels.formula.api as smffrom linearmodels.iv import IV2SLSfrom scipy import stats
people = pd.read_csv("ldl_cimt_individuals.csv")summary_data = pd.read_csv("ldl_cimt_summary.csv")output = Path("outputs")output.mkdir(exist_ok=True)TRUE_EFFECT = 40snps = [name for name in people.columns if name.startswith("snp")]constant = pd.DataFrame({"const": 1.0}, index=people.index)
def report_effect(label, estimate, se): """Print an estimate with its standard error and normal 95% limits.
Args: label: The text to print before the estimate. estimate: The estimate in micrometers per mmol/L. se: The standard error of the estimate.
Returns: The estimate and its standard error. """ z = stats.norm.ppf(0.975) print(f"{label}: {estimate:.1f}, SE {se:.2f}, " f"95% CI [{estimate - z * se:.1f}, {estimate + z * se:.1f}], " f"truth {TRUE_EFFECT}") return estimate, se
ols_fit = smf.ols("cimt ~ ldl", data=people).fit()report_effect("Regression of CIMT on LDL", ols_fit.params["ldl"], ols_fit.bse["ldl"])Regression of CIMT on LDL: 63.1, SE 1.88, 95% CI [59.4, 66.8], truth 40The regression says that each mmol/L of LDL cholesterol comes with 63.1 more micrometers of CIMT, with an interval from 59.4 to 66.8 that excludes the true 40. People with a high value of U have both more LDL cholesterol and thicker arteries, and the regression gives LDL cholesterol the credit for both. A larger sample would narrow the interval around the same wrong value.
One variant: the Wald ratio
Section titled “One variant: the Wald ratio”Take the variant snp03. If it changes CIMT only through LDL cholesterol, its effect on CIMT equals its effect on LDL cholesterol times the causal effect. The causal effect is therefore the ratio of the two regression slopes, the Wald ratio. Its standard error comes from the delta method. The first-order version, the standard error of the CIMT slope divided by the LDL slope, ignores the uncertainty of the LDL slope. The full version adds that uncertainty and, because both slopes come from the same people, their covariance. A one-instrument instrumental variable fit returns the same ratio.
exposure_fit <- lm(ldl ~ snp03, data = people)outcome_fit <- lm(cimt ~ snp03, data = people)beta_x <- coef(exposure_fit)[["snp03"]]beta_y <- coef(outcome_fit)[["snp03"]]se_x <- coef(summary(exposure_fit))["snp03", "Std. Error"]se_y <- coef(summary(outcome_fit))["snp03", "Std. Error"]dosage <- people$snp03 - mean(people$snp03)covariance <- sum(residuals(exposure_fit) * residuals(outcome_fit)) / (nrow(people) - 2) / sum(dosage^2)se_delta <- sqrt(se_y^2 / beta_x^2 + beta_y^2 * se_x^2 / beta_x^4 - 2 * beta_y * covariance / beta_x^3)cat(sprintf("Per allele: LDL %.3f mmol/L (SE %.3f, F %.1f), CIMT %.2f %s\n", beta_x, se_x, (beta_x / se_x)^2, beta_y, sprintf("micrometers (SE %.2f)", se_y)))cat(sprintf("First-order standard error %.2f\n", se_y / abs(beta_x)))ReportEffect("Wald ratio", beta_y / beta_x, se_delta)single_fit <- ivreg(cimt ~ ldl | snp03, data = people)cat(sprintf("ivreg with snp03 alone: %.1f, SE %.2f\n", coef(single_fit)[["ldl"]], coef(summary(single_fit))["ldl", "Std. Error"]))Per allele: LDL 0.199 mmol/L (SE 0.033, F 36.4), CIMT 9.82 micrometers (SE 4.46)First-order standard error 22.43Wald ratio: 49.4, SE 19.96, 95% CI [10.3, 88.5], truth 40ivreg with snp03 alone: 49.4, SE 19.96exposure_fit = smf.ols("ldl ~ snp03", data=people).fit()outcome_fit = smf.ols("cimt ~ snp03", data=people).fit()beta_x = exposure_fit.params["snp03"]beta_y = outcome_fit.params["snp03"]se_x = exposure_fit.bse["snp03"]se_y = outcome_fit.bse["snp03"]dosage = people["snp03"] - people["snp03"].mean()covariance = ((exposure_fit.resid * outcome_fit.resid).sum() / (len(people) - 2) / (dosage**2).sum())se_delta = np.sqrt(se_y**2 / beta_x**2 + beta_y**2 * se_x**2 / beta_x**4 - 2 * beta_y * covariance / beta_x**3)print(f"Per allele: LDL {beta_x:.3f} mmol/L (SE {se_x:.3f}, " f"F {(beta_x / se_x) ** 2:.1f}), CIMT {beta_y:.2f} " f"micrometers (SE {se_y:.2f})")print(f"First-order standard error {se_y / abs(beta_x):.2f}")report_effect("Wald ratio", beta_y / beta_x, se_delta)single_fit = IV2SLS(people["cimt"], constant, people["ldl"], people[["snp03"]]).fit(cov_type="unadjusted", debiased=True)print(f"IV2SLS with snp03 alone: {single_fit.params['ldl']:.1f}, " f"SE {single_fit.std_errors['ldl']:.2f}")Per allele: LDL 0.199 mmol/L (SE 0.033, F 36.4), CIMT 9.82 micrometers (SE 4.46)First-order standard error 22.43Wald ratio: 49.4, SE 19.96, 95% CI [10.3, 88.5], truth 40IV2SLS with snp03 alone: 49.4, SE 19.96Each copy of the allele raises LDL cholesterol by 0.199 mmol/L and CIMT by 9.82 micrometers. The ratio is 49.4 micrometers per mmol/L, with a standard error of 19.96 and an interval from 10.3 to 88.5 that contains the truth. The instrumental variable fits in both languages return the same estimate and the same standard error, 19.96, as the delta method with the covariance term. The first-order standard error, 22.43, is larger here: LDL cholesterol and CIMT vary together within each genotype, so the errors of the two slopes move together, and the covariance term subtracts more than the uncertainty of the LDL slope adds. One variant explains little of the variation of LDL cholesterol, and the standard error is 19.96 / 1.88, about 10.6 times that of the confounded regression.
All variants: two-stage least squares
Section titled “All variants: two-stage least squares”With 15 variants, two-stage least squares first predicts LDL cholesterol from all the genotypes, then regresses CIMT on the prediction. The prediction carries only the part of LDL cholesterol that the genotypes fix, which U cannot reach. The first-stage F statistic tests whether the variants predict LDL cholesterol at all, and its size measures the strength of the instruments. ivreg() takes the instruments after a vertical bar in the formula. IV2SLS takes the outcome, the exogenous columns, the exposure and the instruments as four arguments; cov_type="unadjusted" with debiased=True gives the classical standard error that ivreg() reports. The block also runs the second stage by hand with lm() or ols(), which is the mistake to avoid.
iv_formula <- as.formula(paste("cimt ~ ldl |", paste(snps, collapse = " + ")))iv_fit <- ivreg(iv_formula, data = people)iv_summary <- summary(iv_fit, diagnostics = TRUE)first_stage <- lm(reformulate(snps, "ldl"), data = people)people$ldl_predicted <- fitted(first_stage)second_stage <- lm(cimt ~ ldl_predicted, data = people)full_f <- iv_summary$diagnostics["Weak instruments", "statistic"]cat(sprintf("First stage: F = %.1f on %d and %d df, R squared = %.3f\n", full_f, iv_summary$diagnostics["Weak instruments", "df1"], iv_summary$diagnostics["Weak instruments", "df2"], summary(first_stage)$r.squared))ReportEffect("Two-stage least squares", coef(iv_fit)[["ldl"]], coef(iv_summary)["ldl", "Std. Error"])cat(sprintf("Second stage by hand: %.1f, naive SE %.2f\n", coef(second_stage)[["ldl_predicted"]], coef(summary(second_stage))["ldl_predicted", "Std. Error"]))cat(sprintf("Residual SD: by hand %.1f, ivreg %.1f\n", sigma(second_stage), iv_summary$sigma))First stage: F = 25.7 on 15 and 3984 df, R squared = 0.088Two-stage least squares: 35.1, SE 6.51, 95% CI [22.4, 47.9], truth 40Second stage by hand: 35.1, naive SE 7.15Residual SD: by hand 120.4, ivreg 109.6iv_fit = IV2SLS(people["cimt"], constant, people["ldl"], people[snps]).fit(cov_type="unadjusted", debiased=True)diagnostics = iv_fit.first_stage.diagnostics.loc["ldl"]first_stage = sm.OLS(people["ldl"], sm.add_constant(people[snps])).fit()people["ldl_predicted"] = first_stage.fittedvaluessecond_stage = smf.ols("cimt ~ ldl_predicted", data=people).fit()full_f = diagnostics["f.stat"]print(f"First stage: F = {full_f:.1f} on {len(snps)} and " f"{int(first_stage.df_resid)} df, " f"R squared = {diagnostics['rsquared']:.3f}")report_effect("Two-stage least squares", iv_fit.params["ldl"], iv_fit.std_errors["ldl"])print(f"Second stage by hand: {second_stage.params['ldl_predicted']:.1f}, " f"naive SE {second_stage.bse['ldl_predicted']:.2f}")print(f"Residual SD: by hand {np.sqrt(second_stage.scale):.1f}, " f"IV2SLS {np.sqrt(iv_fit.s2):.1f}")First stage: F = 25.7 on 15 and 3984 df, R squared = 0.088Two-stage least squares: 35.1, SE 6.51, 95% CI [22.4, 47.9], truth 40Second stage by hand: 35.1, naive SE 7.15Residual SD: by hand 120.4, IV2SLS 109.6The 15 variants explain 8.8% of the variance of LDL cholesterol, with a first-stage F of 25.7 on 15 and 3,984 degrees of freedom. The estimate is 35.1 micrometers per mmol/L, with a standard error of 6.51 and an interval from 22.4 to 47.9 that contains the truth. R and Python agree on every printed digit. The second stage by hand returns the same 35.1 with a standard error of 7.15. Its residuals are CIMT minus the slope times predicted LDL cholesterol, where the model needs CIMT minus the slope times measured LDL cholesterol, so its residual standard deviation is 120.4 instead of 109.6. The two standard errors differ by the ratio of these two numbers. The manual route gives the two-stage least squares estimate with the wrong standard error, the wrong interval and the wrong p-value.
Weak instruments
Section titled “Weak instruments”The strength of the instruments decides how much of the confounding survives. In one sample, the first stage fits some of the chance correlation between the genotypes and U, and that part of the predicted LDL cholesterol is confounded again. With strong instruments the share is small. With weak ones the estimate moves toward the observational regression. The block cuts the 4,000 people into 40 studies of 100 and repeats both analyses in each study.
study_size <- 100studies <- nrow(people) / study_sizesmall <- data.frame(f = numeric(studies), tsls = numeric(studies), ols = numeric(studies))for (study in seq_len(studies)) { rows <- people[((study - 1) * study_size + 1):(study * study_size), ] first <- lm(reformulate(snps, "ldl"), data = rows) small$f[study] <- summary(first)$fstatistic[["value"]] small$tsls[study] <- coef(ivreg(iv_formula, data = rows))[["ldl"]] small$ols[study] <- coef(lm(cimt ~ ldl, data = rows))[["ldl"]]}remaining <- (mean(small$tsls) - true_effect) / (mean(small$ols) - true_effect)cat(sprintf("%d studies of %d people, mean first-stage F %.2f\n", studies, study_size, mean(small$f)))cat(sprintf("Mean estimate: two-stage least squares %.1f, %s %.1f, %s %d\n", mean(small$tsls), "regression", mean(small$ols), "truth", true_effect))cat(sprintf("Share of the regression bias that remains %.2f, 1 / F = %.2f\n", remaining, 1 / mean(small$f)))40 studies of 100 people, mean first-stage F 1.69Mean estimate: two-stage least squares 55.6, regression 63.2, truth 40Share of the regression bias that remains 0.67, 1 / F = 0.59study_size = 100studies = len(people) // study_sizeresults = []for study in range(studies): rows = people.iloc[study * study_size:(study + 1) * study_size] fit = IV2SLS(rows["cimt"], constant.loc[rows.index], rows["ldl"], rows[snps]).fit(cov_type="unadjusted", debiased=True) results.append({ "f": fit.first_stage.diagnostics.loc["ldl", "f.stat"], "tsls": fit.params["ldl"], "ols": smf.ols("cimt ~ ldl", data=rows).fit().params["ldl"]})small = pd.DataFrame(results)remaining = ((small["tsls"].mean() - TRUE_EFFECT) / (small["ols"].mean() - TRUE_EFFECT))print(f"{studies} studies of {study_size} people, " f"mean first-stage F {small['f'].mean():.2f}")print(f"Mean estimate: two-stage least squares {small['tsls'].mean():.1f}, " f"regression {small['ols'].mean():.1f}, truth {TRUE_EFFECT}")print(f"Share of the regression bias that remains {remaining:.2f}, " f"1 / F = {1 / small['f'].mean():.2f}")40 studies of 100 people, mean first-stage F 1.69Mean estimate: two-stage least squares 55.6, regression 63.2, truth 40Share of the regression bias that remains 0.67, 1 / F = 0.59With 100 people per study the mean first-stage F is 1.69. The two-stage estimates average 55.6, much closer to the regression average of 63.2 than to the truth of 40: 0.67 of the confounding bias remains. Burgess and Thompson, 2011 describe this direction, toward the confounded observational association, with a size that depends on the F statistic. Burgess, Davies, and Thompson, 2016 give a relative bias of 10% for an F parameter of 10 in one sample, which is the approximation 1 / F. Here 1 / F is 0.59, a rough guide at this strength. With all 4,000 people the F of 25.7 puts 1 / F near 0.04, or about 0.9 of the 63.1 - 40 = 23.1 micrometers per mmol/L of confounding bias, which is small next to the standard error of 6.51. The interval of a weak-instrument estimate is also misleading, because it is centered on a biased value. Burgess and Thompson show that the rule of thumb F > 10 does not remove the bias, and that choosing instruments or studies by their observed F makes it worse.
Two samples and summary data
Section titled “Two samples and summary data”Most Mendelian randomization studies have no individual data. They take the effect of each variant on the exposure from one genome-wide association study and its effect on the outcome from another, as in the summary table. Each variant gives a ratio estimate, beta_outcome / beta_exposure, and the methods below combine the 15 ratios.
- The inverse-variance weighted (IVW) estimate is the slope of a weighted regression of
beta_outcomeonbeta_exposurethrough the origin, with weights 1 /se_outcome². Its fixed-effect standard error assumes that every variant estimates the same effect, and it is the regression standard error divided by the residual standard error. The multiplicative random-effects standard error multiplies the fixed-effect one by the residual standard error when that exceeds 1, so it grows with the heterogeneity of the ratios. Cochran’s Q tests that heterogeneity. - MR-Egger adds an intercept to the same regression, with every variant oriented so that its effect on the exposure is positive. The slope estimates the causal effect and the intercept estimates the average direct effect of an allele on the outcome.
- The weighted median sorts the 15 ratios, gives each a weight of
beta_exposure² /se_outcome², and takes the ratio at half of the total weight. Its standard error comes from a parametric bootstrap that redraws both effects of every variant 10,000 times.
The R tab also checks the hand code against the MendelianRandomization package, whose mr_input() takes the four columns. The Python tab has the hand code only. mr_median() seeds its bootstrap with 314159265 by default.
#' Compute the inverse-variance weighted estimate from summary data.#'#' @param table One row per variant of the summary table.#' @return The estimate, both standard errors, sigma and the Q p-value.IvwEstimate <- function(table) { fit <- lm(beta_outcome ~ 0 + beta_exposure, data = table, weights = 1 / se_outcome^2) sigma <- summary(fit)$sigma se_fixed <- coef(summary(fit))[1, "Std. Error"] / sigma c(estimate = coef(fit)[[1]], se_fixed = se_fixed, se_random = se_fixed * max(1, sigma), sigma = sigma, p_q = pchisq(sigma^2 * (nrow(table) - 1), nrow(table) - 1, lower.tail = FALSE))}
#' Compute the MR-Egger slope and intercept from summary data.#'#' @param table One row per variant, with every beta_exposure positive.#' @return The slope, the intercept, their standard errors and the#' p-value of the intercept.EggerEstimate <- function(table) { fit <- lm(beta_outcome ~ beta_exposure, data = table, weights = 1 / se_outcome^2) estimates <- coef(summary(fit)) se <- estimates[, "Std. Error"] / min(1, summary(fit)$sigma) intercept <- estimates["(Intercept)", "Estimate"] c(slope = estimates["beta_exposure", "Estimate"], se_slope = se[["beta_exposure"]], intercept = intercept, se_intercept = se[["(Intercept)"]], p_intercept = 2 * pnorm(-abs(intercept / se[["(Intercept)"]])))}
#' Find the weighted median of ratio estimates by linear interpolation.#'#' @param ratio The ratio estimate of each variant.#' @param weight The weight of each variant.#' @return The ratio at which the standardized cumulative weight is 0.5.WeightedMedian <- function(ratio, weight) { rank <- order(ratio) ratio <- ratio[rank] weight <- weight[rank] position <- (cumsum(weight) - weight / 2) / sum(weight) below <- max(which(position < 0.5)) ratio[below] + (ratio[below + 1] - ratio[below]) * (0.5 - position[below]) / (position[below + 1] - position[below])}
#' Compute the weighted median with a bootstrap standard error.#'#' @param table One row per variant of the summary table.#' @param draws The number of parametric bootstrap draws.#' @return The estimate and its standard error.MedianEstimate <- function(table, draws = 10000) { set.seed(1) weight <- (table$beta_exposure / table$se_outcome)^2 drawn_x <- matrix(rnorm(nrow(table) * draws, table$beta_exposure, table$se_exposure), nrow = nrow(table)) drawn_y <- matrix(rnorm(nrow(table) * draws, table$beta_outcome, table$se_outcome), nrow = nrow(table)) resampled <- numeric(draws) for (draw in seq_len(draws)) { resampled[draw] <- WeightedMedian(drawn_y[, draw] / drawn_x[, draw], weight) } c(estimate = WeightedMedian(table$beta_outcome / table$beta_exposure, weight), se = sd(resampled))}
valid <- summary_data[summary_data$scenario == "valid", ]cat(sprintf("Mean F of a variant in the exposure sample %.1f\n", mean((valid$beta_exposure / valid$se_exposure)^2)))ivw <- IvwEstimate(valid)egger <- EggerEstimate(valid)median_fit <- MedianEstimate(valid)ReportEffect("IVW, fixed effect", ivw[["estimate"]], ivw[["se_fixed"]])ReportEffect("IVW, random effects", ivw[["estimate"]], ivw[["se_random"]])cat(sprintf("Residual standard error %.3f, Cochran's Q p = %.2f\n", ivw[["sigma"]], ivw[["p_q"]]))ReportEffect("MR-Egger slope", egger[["slope"]], egger[["se_slope"]])cat(sprintf("MR-Egger intercept %.2f, SE %.2f, p = %.2f\n", egger[["intercept"]], egger[["se_intercept"]], egger[["p_intercept"]]))ReportEffect("Weighted median", median_fit[["estimate"]], median_fit[["se"]])
mr_data <- mr_input(bx = valid$beta_exposure, bxse = valid$se_exposure, by = valid$beta_outcome, byse = valid$se_outcome, snps = valid$variant)package_fixed <- mr_ivw(mr_data, model = "fixed")package_random <- mr_ivw(mr_data, model = "random")package_egger <- mr_egger(mr_data)package_median <- mr_median(mr_data, weighting = "weighted")cat(sprintf("mr_ivw fixed: %.3f, SE %.3f; by hand %.3f, SE %.3f\n", package_fixed@Estimate, package_fixed@StdError, ivw[["estimate"]], ivw[["se_fixed"]]))cat(sprintf("mr_ivw random: %.3f, SE %.3f; by hand %.3f, SE %.3f\n", package_random@Estimate, package_random@StdError, ivw[["estimate"]], ivw[["se_random"]]))cat(sprintf("mr_egger: slope %.3f, SE %.3f, intercept %.3f, %s\n", package_egger@Estimate, package_egger@StdError.Est, package_egger@Intercept, sprintf("p = %.3f", package_egger@Pvalue.Int)))cat(sprintf("by hand: slope %.3f, SE %.3f, intercept %.3f, p = %.3f\n", egger[["slope"]], egger[["se_slope"]], egger[["intercept"]], egger[["p_intercept"]]))cat(sprintf("mr_median: %.3f, SE %.3f, or %.3f with seed 1; %s\n", package_median@Estimate, package_median@StdError, mr_median(mr_data, seed = 1)@StdError, sprintf("by hand %.3f, SE %.3f", median_fit[["estimate"]], median_fit[["se"]])))Mean F of a variant in the exposure sample 108.4IVW, fixed effect: 37.4, SE 2.09, 95% CI [33.3, 41.5], truth 40IVW, random effects: 37.4, SE 2.23, 95% CI [33.1, 41.8], truth 40Residual standard error 1.067, Cochran's Q p = 0.32MR-Egger slope: 42.3, SE 4.57, 95% CI [33.4, 51.3], truth 40MR-Egger intercept -0.61, SE 0.50, p = 0.22Weighted median: 40.1, SE 3.17, 95% CI [33.9, 46.3], truth 40mr_ivw fixed: 37.449, SE 2.092; by hand 37.449, SE 2.092mr_ivw random: 37.449, SE 2.232; by hand 37.449, SE 2.232mr_egger: slope 42.314, SE 4.569, intercept -0.612, p = 0.225by hand: slope 42.314, SE 4.569, intercept -0.612, p = 0.225mr_median: 40.130, SE 3.241, or 3.193 with seed 1; by hand 40.130, SE 3.172def ivw_estimate(table): """Compute the inverse-variance weighted estimate from summary data.
Args: table: One row per variant of the summary table.
Returns: The estimate, both standard errors, sigma and the Q p-value. """ fit = sm.WLS(table["beta_outcome"], table[["beta_exposure"]], weights=1 / table["se_outcome"] ** 2).fit() sigma = np.sqrt(fit.scale) se_fixed = fit.bse["beta_exposure"] / sigma return {"estimate": fit.params["beta_exposure"], "se_fixed": se_fixed, "se_random": se_fixed * max(1.0, sigma), "sigma": sigma, "p_q": stats.chi2.sf(fit.scale * (len(table) - 1), len(table) - 1)}
def egger_estimate(table): """Compute the MR-Egger slope and intercept from summary data.
Args: table: One row per variant, with every beta_exposure positive.
Returns: The slope, the intercept, their standard errors and p-value. """ fit = sm.WLS(table["beta_outcome"], sm.add_constant(table[["beta_exposure"]]), weights=1 / table["se_outcome"] ** 2).fit() se = fit.bse / min(1.0, np.sqrt(fit.scale)) intercept = fit.params["const"] return {"slope": fit.params["beta_exposure"], "se_slope": se["beta_exposure"], "intercept": intercept, "se_intercept": se["const"], "p_intercept": 2 * stats.norm.sf(abs(intercept / se["const"]))}
def weighted_median(ratio, weight): """Find the weighted median of ratio estimates by linear interpolation.
Args: ratio: The ratio estimate of each variant. weight: The weight of each variant.
Returns: The ratio at which the standardized cumulative weight is 0.5. """ rank = np.argsort(ratio) ratio = np.asarray(ratio)[rank] weight = np.asarray(weight)[rank] position = (np.cumsum(weight) - weight / 2) / weight.sum() below = np.flatnonzero(position < 0.5).max() return ratio[below] + ((ratio[below + 1] - ratio[below]) * (0.5 - position[below]) / (position[below + 1] - position[below]))
def median_estimate(table, draws=10000): """Compute the weighted median with a bootstrap standard error.
Args: table: One row per variant of the summary table. draws: The number of parametric bootstrap draws.
Returns: The estimate and its standard error. """ rng = np.random.default_rng(1) weight = (table["beta_exposure"] / table["se_outcome"]) ** 2 drawn_x = rng.normal(table["beta_exposure"], table["se_exposure"], size=(draws, len(table))) drawn_y = rng.normal(table["beta_outcome"], table["se_outcome"], size=(draws, len(table))) resampled = np.empty(draws) for draw in range(draws): resampled[draw] = weighted_median(drawn_y[draw] / drawn_x[draw], weight) estimate = weighted_median(table["beta_outcome"] / table["beta_exposure"], weight) return {"estimate": estimate, "se": resampled.std(ddof=1)}
valid = summary_data[summary_data["scenario"] == "valid"]mean_f = ((valid["beta_exposure"] / valid["se_exposure"]) ** 2).mean()print(f"Mean F of a variant in the exposure sample {mean_f:.1f}")ivw = ivw_estimate(valid)egger = egger_estimate(valid)median_fit = median_estimate(valid)report_effect("IVW, fixed effect", ivw["estimate"], ivw["se_fixed"])report_effect("IVW, random effects", ivw["estimate"], ivw["se_random"])print(f"Residual standard error {ivw['sigma']:.3f}, " f"Cochran's Q p = {ivw['p_q']:.2f}")report_effect("MR-Egger slope", egger["slope"], egger["se_slope"])print(f"MR-Egger intercept {egger['intercept']:.2f}, " f"SE {egger['se_intercept']:.2f}, p = {egger['p_intercept']:.2f}")report_effect("Weighted median", median_fit["estimate"], median_fit["se"])Mean F of a variant in the exposure sample 108.4IVW, fixed effect: 37.4, SE 2.09, 95% CI [33.3, 41.5], truth 40IVW, random effects: 37.4, SE 2.23, 95% CI [33.1, 41.8], truth 40Residual standard error 1.067, Cochran's Q p = 0.32MR-Egger slope: 42.3, SE 4.57, 95% CI [33.4, 51.3], truth 40MR-Egger intercept -0.61, SE 0.50, p = 0.22Weighted median: 40.1, SE 3.15, 95% CI [34.0, 46.3], truth 40With valid instruments the intervals of all three methods contain the truth. IVW gives 37.4 with a fixed-effect standard error of 2.09; the residual standard error is 1.067, so the random-effects standard error is 2.09 × 1.067 = 2.23. Cochran’s Q gives p = 0.32, with no sign of heterogeneity. MR-Egger gives 42.3 with a standard error of 4.57, more than twice that of IVW, because it also estimates an intercept from the same 15 points. The intercept is -0.61 with p = 0.22. The weighted median gives 40.1, with a bootstrap standard error of 3.17 in R and 3.15 in Python, since the two languages draw different random numbers. The package and the hand code agree to three decimals on every IVW and MR-Egger number and on the weighted median estimate, 40.130. The bootstrap standard error of the weighted median is 3.241 with the default seed and 3.193 with seed 1, so the third value, 3.172 by hand, differs from them by simulation noise alone.
Pleiotropy
Section titled “Pleiotropy”The exclusion restriction says that a variant reaches the outcome only through the exposure. It fails when a variant has a second effect on the outcome, a pleiotropic effect, and it is the assumption that fails most often in practice. Each method needs its own form of it. IVW needs every variant to be valid, with one exception: it stays unbiased when the direct effects average zero and are independent of the effects on LDL cholesterol, and its random-effects standard error then covers the extra spread. MR-Egger allows every variant to be invalid under the InSIDE assumption: the direct effects of the variants on the outcome are independent of their effects on the exposure, as the simulation draws them. The weighted median needs more than half of the weight to come from valid variants.
The block runs every method on the four scenarios and draws the directional scenario with the fitted lines. In the balanced and directional scenarios every variant has a direct effect, so no variant is valid. The last row gives the share of the weight, beta_exposure² / se_outcome², that comes from invalid variants.
z <- qnorm(0.975)scenarios <- c("valid", "balanced", "minority", "directional")methods <- c("IVW, fixed effect", "IVW, random effects", "MR-Egger slope", "Weighted median", "MR-Egger intercept", "Intercept p-value", "Cochran's Q p-value", "Weight share invalid")cells <- matrix("", length(methods), length(scenarios), dimnames = list(methods, scenarios))for (scenario in scenarios) { table <- summary_data[summary_data$scenario == scenario, ] ivw <- IvwEstimate(table) egger <- EggerEstimate(table) median_fit <- MedianEstimate(table) estimate <- c(ivw[["estimate"]], ivw[["estimate"]], egger[["slope"]], median_fit[["estimate"]], egger[["intercept"]]) se <- c(ivw[["se_fixed"]], ivw[["se_random"]], egger[["se_slope"]], median_fit[["se"]], egger[["se_intercept"]]) weight <- (table$beta_exposure / table$se_outcome)^2 cells[, scenario] <- c( sprintf("%.1f [%.1f, %.1f]", estimate, estimate - z * se, estimate + z * se), sprintf("%.2f", egger[["p_intercept"]]), sprintf("%.2g", ivw[["p_q"]]), sprintf("%.2f", sum(weight[table$direct_effect != 0]) / sum(weight)) )}cat(sprintf("Truth: %d micrometers per mmol/L in every scenario\n", true_effect))options(width = 100)print(noquote(cells))
# The last pass of the loop was the directional scenario.fitted_lines <- data.frame( method = factor(c("IVW", "MR-Egger", "Weighted median", "Truth"), levels = c("IVW", "MR-Egger", "Weighted median", "Truth")), intercept = c(0, egger[["intercept"]], 0, 0), slope = c(ivw[["estimate"]], egger[["slope"]], median_fit[["estimate"]], true_effect))scatter <- ggplot(table, aes(beta_exposure, beta_outcome)) + geom_abline(data = fitted_lines, linewidth = 0.8, aes(intercept = intercept, slope = slope, color = method, linetype = method)) + geom_errorbar(aes(ymin = beta_outcome - z * se_outcome, ymax = beta_outcome + z * se_outcome), width = 0, color = "gray35") + geom_errorbar(aes(xmin = beta_exposure - z * se_exposure, xmax = beta_exposure + z * se_exposure), width = 0, color = "gray35", orientation = "y") + geom_point(size = 2) + scale_color_manual(values = c("#eb6834", "#2a78d6", "#1baf7a", "gray20")) + scale_linetype_manual(values = c("solid", "solid", "solid", "dashed")) + scale_x_continuous(limits = c(0, 0.28), expand = c(0, 0)) + scale_y_continuous(limits = c(0, 17), expand = c(0, 0)) + labs(x = "Effect of one allele on LDL cholesterol (mmol/L)", y = "Effect of one allele on CIMT (micrometers)", color = NULL, linetype = NULL) + theme_minimal(base_size = 12) + theme(legend.position = "top", panel.grid.minor = element_blank())ggsave("outputs/mr-directional-scatter-r.png", scatter, width = 6.5, height = 5, dpi = 150, bg = "white")Truth: 40 micrometers per mmol/L in every scenario valid balanced minority directionalIVW, fixed effect 37.4 [33.3, 41.5] 39.0 [34.9, 43.1] 43.6 [39.5, 47.7] 60.5 [56.4, 64.6]IVW, random effects 37.4 [33.1, 41.8] 39.0 [22.9, 55.1] 43.6 [35.4, 51.8] 60.5 [51.0, 70.1]MR-Egger slope 42.3 [33.4, 51.3] 50.2 [16.2, 84.3] 42.1 [24.4, 59.8] 47.7 [28.6, 66.7]Weighted median 40.1 [33.9, 46.3] 37.8 [28.2, 47.4] 40.9 [33.5, 48.3] 57.2 [49.0, 65.4]MR-Egger intercept -0.6 [-1.6, 0.4] -1.4 [-5.2, 2.3] 0.2 [-1.8, 2.1] 1.6 [-0.5, 3.7]Intercept p-value 0.22 0.46 0.85 0.13Cochran's Q p-value 0.32 6.3e-38 5.8e-07 2.2e-10Weight share invalid 0.00 1.00 0.25 1.00
z = stats.norm.ppf(0.975)scenarios = ["valid", "balanced", "minority", "directional"]methods = ["IVW, fixed effect", "IVW, random effects", "MR-Egger slope", "Weighted median", "MR-Egger intercept", "Intercept p-value", "Cochran's Q p-value", "Weight share invalid"]cells = {}for scenario in scenarios: table = summary_data[summary_data["scenario"] == scenario] ivw = ivw_estimate(table) egger = egger_estimate(table) median_fit = median_estimate(table) estimate = [ivw["estimate"], ivw["estimate"], egger["slope"], median_fit["estimate"], egger["intercept"]] se = [ivw["se_fixed"], ivw["se_random"], egger["se_slope"], median_fit["se"], egger["se_intercept"]] cells[scenario] = [ f"{value:.1f} [{value - z * error:.1f}, {value + z * error:.1f}]" for value, error in zip(estimate, se)] weight = (table["beta_exposure"] / table["se_outcome"]) ** 2 invalid_share = weight[table["direct_effect"] != 0].sum() / weight.sum() cells[scenario] += [f"{egger['p_intercept']:.2f}", f"{ivw['p_q']:.2g}", f"{invalid_share:.2f}"]print(f"Truth: {TRUE_EFFECT} micrometers per mmol/L in every scenario")print(pd.DataFrame(cells, index=methods).to_string())
# The last pass of the loop was the directional scenario.lines = {"IVW": (0.0, ivw["estimate"], "#eb6834", "-"), "MR-Egger": (egger["intercept"], egger["slope"], "#2a78d6", "-"), "Weighted median": (0.0, median_fit["estimate"], "#1baf7a", "-"), "Truth": (0.0, TRUE_EFFECT, "0.2", "--")}grid = np.array([0, 0.28])fig, ax = plt.subplots(figsize=(6.5, 5))for label, (intercept, slope, color, style) in lines.items(): ax.plot(grid, intercept + slope * grid, color=color, linestyle=style, linewidth=1.6, label=label)ax.errorbar(table["beta_exposure"], table["beta_outcome"], xerr=z * table["se_exposure"], yerr=z * table["se_outcome"], fmt="o", color="black", ecolor="0.35", markersize=5, linewidth=1)ax.set(xlim=(0, 0.28), ylim=(0, 17), xlabel="Effect of one allele on LDL cholesterol (mmol/L)", ylabel="Effect of one allele on CIMT (micrometers)")ax.legend(frameon=False, loc="upper left")ax.spines[["top", "right"]].set_visible(False)fig.tight_layout()fig.savefig(output / "mr-directional-scatter-python.png", dpi=150)plt.close(fig)Truth: 40 micrometers per mmol/L in every scenario valid balanced minority directionalIVW, fixed effect 37.4 [33.3, 41.5] 39.0 [34.9, 43.1] 43.6 [39.5, 47.7] 60.5 [56.4, 64.6]IVW, random effects 37.4 [33.1, 41.8] 39.0 [22.9, 55.1] 43.6 [35.4, 51.8] 60.5 [51.0, 70.1]MR-Egger slope 42.3 [33.4, 51.3] 50.2 [16.2, 84.3] 42.1 [24.4, 59.8] 47.7 [28.6, 66.7]Weighted median 40.1 [34.0, 46.3] 37.8 [28.3, 47.3] 40.9 [33.4, 48.3] 57.2 [49.1, 65.3]MR-Egger intercept -0.6 [-1.6, 0.4] -1.4 [-5.2, 2.3] 0.2 [-1.8, 2.1] 1.6 [-0.5, 3.7]Intercept p-value 0.22 0.46 0.85 0.13Cochran's Q p-value 0.32 6.3e-38 5.8e-07 2.2e-10Weight share invalid 0.00 1.00 0.25 1.00
With balanced pleiotropy, IVW stays close to the truth at 39.0, but Cochran’s Q gives p = 6.3e-38 and the fixed-effect interval from 34.9 to 43.1 ignores the spread of the 15 ratios. The random-effects interval, from 22.9 to 55.1, is about four times as wide and is the one to report. The weighted median gives 37.8 and MR-Egger 50.2, with the widest interval of the table.
With directional pleiotropy most alleles add a few micrometers of CIMT of their own, so most ratios are too large. IVW gives 60.5 and the weighted median 57.2, and neither interval contains 40. The two methods agree with each other and are both wrong: no variant is valid, so the weighted median has no valid majority to find. MR-Egger gives 47.7, with an interval from 28.6 to 66.7 that contains the truth, at the price of an interval twice as wide as that of random-effects IVW. Its intercept is 1.6, with an interval from -0.5 to 3.7 and p = 0.13. The intercept fails to reach significance although every variant has a direct effect on CIMT, so a nonsignificant Egger intercept does not show the absence of pleiotropy. Cochran’s Q, with p = 2.2e-10, is the signal that something is wrong here, and it does not say what.
The minority column is the case that the weighted median is built for: 4 of the 15 variants are invalid and carry 0.25 of the weight. It shares its people with the valid column, and the direct effects of those 4 variants move IVW from 37.4 to 43.6 and the weighted median from 40.1 to 40.9. The median of the ratios stays anchored by the valid majority. IVW does not miss here, since both of its intervals still contain 40, the fixed-effect one from 39.5 upward. A pleiotropic bias does not shrink as the samples grow, while the interval does, so a larger study with the same variants would move the IVW interval off the truth. MR-Egger gives 42.1 with an interval from 24.4 to 59.8, and its intercept of 0.2, with p = 0.85, gives no sign of the 4 invalid variants. Cochran’s Q gives p = 5.8e-07, which flags the heterogeneity without naming the variants behind it.
In the figure, most variants sit above the dashed line of the truth. The IVW and weighted median lines pass through the origin and follow the points upward, and the MR-Egger line starts at 1.6 micrometers and rises less steeply.
The three assumptions
Section titled “The three assumptions”A variant is an instrument for LDL cholesterol under three conditions. Relevance means that the variant changes LDL cholesterol. The first-stage F of 25.7 and the per-variant F statistics test it, and it is the only one of the three that the data can check. Independence means that the variant is independent of U and of every other cause of CIMT. Alleles are assigned at random at conception within a family, which is the reason for the name, but a population that mixes ancestry groups with different allele frequencies and different mean CIMT breaks it. The exclusion restriction means that the variant changes CIMT only through LDL cholesterol. The three pleiotropy scenarios break it, and the data cannot prove that it holds: the directional scenario gives a nonsignificant intercept and two methods that agree, with no valid variant at all, and the minority scenario gives an intercept with p = 0.85.
Under these three conditions the methods estimate the effect of LDL cholesterol only if that effect is the same for everyone, or under further conditions on how it varies, which is why the simulation uses one effect of 40 for all.
Mistakes to avoid
Section titled “Mistakes to avoid”Do not choose the variants and estimate their effects on the exposure in the same sample. The variants that pass a significance threshold are those whose effects were overestimated by chance, a winner’s curse, and in a two-sample analysis an inflated beta_exposure shrinks each ratio toward zero. Take the exposure effects from a sample that played no part in the selection.
Do not treat two samples that share participants as independent when the instruments are weak. Burgess, Davies, and Thompson describe the bias of a one-sample analysis as toward the observational association and that of a two-sample analysis without overlap as toward the null, and they find that for a continuous outcome the bias grows linearly with the proportion of overlap.
Do not ignore population stratification. When allele frequencies and the outcome both differ between ancestry groups, a variant predicts the outcome through ancestry, which breaks the independence assumption. Adjust both association studies for the principal components of ancestry, as the population structure page computes them, or restrict the samples to one ancestry group.
Do not read a Mendelian randomization estimate as the effect of a drug. A variant shifts LDL cholesterol from conception onward, and the estimate of 40 micrometers per mmol/L describes a lifelong difference. A statin started at 60 years of age lowers LDL cholesterol for the remaining years only, so its effect on CIMT can be smaller. Burgess and colleagues, 2012 discuss the use of Mendelian randomization to assess the potential benefit of a clinical intervention.
Scientific references
Section titled “Scientific references”Davey Smith and Ebrahim, 2003 describe Mendelian randomization, the use of the random assortment of genes at conception to assess the causal nature of environmental exposures, and its limitations.
Burgess, Butterworth, and Thompson, 2013 show how the regression coefficients of many variants from summarized data can be combined to estimate a causal effect, and compare the result with individual data.
Bowden, Davey Smith, and Burgess, 2015 adapt Egger regression to Mendelian randomization with invalid instruments, for effect estimation and the detection of bias from pleiotropy.
Bowden and colleagues, 2016 introduce the weighted median estimator, which is consistent when up to 50% of the information comes from invalid instruments.
Burgess and Thompson, 2011 show that weak instrument bias acts in the direction of the confounded observational association and grows as the F statistic decreases.
Burgess, Davies, and Thompson, 2016 quantify the bias due to participant overlap in two-sample Mendelian randomization.
Burgess and colleagues, 2012 discuss the use of Mendelian randomization to assess the potential benefit of a clinical intervention.
The ivreg package by Fox, Kleiber, and Zeileis fits instrumental-variables regression by two-stage least squares, with diagnostics.
The MendelianRandomization package by Burgess and Yavorska implements the inverse-variance weighted, MR-Egger and median methods for summarized data in R.
Sheppard and colleagues, 2026 archive release 7.1 of linearmodels, the Python library whose IV2SLS estimator this page uses.
Further reading
Section titled “Further reading”The MendelianRandomization vignette covers mr_input(), the inverse-variance weighted, median and MR-Egger methods with their options, and the other methods of the package. The ivreg introduction explains the formula with two parts on the right-hand side and shows the weak instrument test in the output of summary(). The linearmodels guide to instrumental variables covers IV2SLS, the cov_type options and the tests of identification in the first_stage attribute. On this site, the target trial emulation page estimates a drug effect from health records, and the page on confounding and causal diagrams explains the confounding that an instrument avoids.