This book presents code examples from Hernán and Robins (2020), which is available in draft form from the following webpage.

The R code is based on the code by Joy Shi and Sean McGrath given here.

The Stata code is based on the code by Eleanor Murray and Roger Logan given here.

Packages to install

To install the R packages required for this book please copy/fork the repository. It is easiest to open the repo in RStudio as an RStudio project, by doubling click the .Rproj file. This makes sure that R’s working directory is at the top level of the repo. If you don’t want to open the repo as a project set the working directory to the top level of the repo directories using setwd(). Then run:

# install.packages('devtools') # uncomment if devtools not
# installed

Downloading the datasets

We assume that you have downloaded the data from the Causal Inference Book website and saved it to a data subdirectory. You can do this manually or with the following code (nb. we use the here package to reference the data subdirectory).

dataurls <- list()
dataurls[[1]] <- ""
dataurls[[2]] <- ""
dataurls[[3]] <- ""
dataurls[[4]] <- ""

temp <- tempfile()
for (i in 1:3) {
    download.file(dataurls[[i]], temp)
    unzip(temp, exdir = "data")

download.file(dataurls[[4]], here("data", "nhefs.csv"))


Hernán, Miguel A, and James M Robins. 2020. Causal Inference: What If. Boca Raton: Chapman & Hall/CRC.