Mendelian Randomisation from Scratch

A worked example in R: causal inference from genetic instruments, built up one line of matrix algebra at a time

Author
Published

July 2026

Welcome

Suppose you notice that people with higher blood levels of some biomarker also tend to develop heart disease more often. Does the biomarker cause the disease, so that lowering it would help patients? Or do the two just travel together because something else (diet, wealth, an unmeasured illness) pushes both up at once?

Observational data alone cannot separate those two stories. A randomised trial can, but trials are slow, expensive, sometimes unethical, and often simply unavailable. Mendelian randomisation (MR) is a way to borrow the logic of a randomised trial from a source that already exists in every one of us: the roughly random shuffle of genetic variants we each inherit at conception.

This book works one full example end to end, in R, with nothing hidden inside a package. Every estimator is a few lines of matrix algebra you can read, run, and change. By the last chapter you will have coded two-stage least squares, inverse-variance weighting, MR-Egger, and the weighted median by hand, watched each one recover a causal effect we planted in synthetic data, and seen exactly how and when they break.

Who this is for

You have some R and some regression. You may have heard “MR” in a talk or a paper and want to know what is actually going on underneath. You do not need a genetics background; the four ideas from genetics that MR relies on are introduced as they come up.

What you will build

Chapter What you code What you learn
1 A confounded observational estimate Why naïve regression misleads
2 (no code) Genetic variants as a natural experiment; the three instrument assumptions
3 A seeded data simulator A causal model with a known answer to check against
4 Two-stage least squares One-sample MR, cross-checked against ivreg
5 Inverse-variance weighting Two-sample MR from summary statistics
6 MR-Egger, weighted median Diagnosing and surviving pleiotropy
7 (no code) How to read an MR paper critically

A note on the data

Important

Every number in this book comes from simulated data. No real cohort, biobank, or patient records are used or shared anywhere in this repository. Simulating the data is the point: because we choose the true causal effect ourselves, we can hold each method up against the right answer and see whether it delivers.

The full source, including the simulator and every estimator, lives in the GitHub repository. Use the </> Code links in the top-right of any page to see or copy the R behind a figure.

Turn to Chapter 1 to meet the problem MR is built to solve.