# LATE in a medical trial: vitamin A supplements and child mortality (Aceh, Indonesia)
# Dr Nicky Grant, drnickygrant.com. Needs: install.packages("AER")
suppressPackageStartupMessages(library(AER))   # ivreg(), coeftest(), vcovHC()

# The six published cell counts (Sommer and Zeger 1991): z = 1 if the child's
# village was offered vitamin A, w = 1 if the child received it,
# died = 1 if the child died during follow-up
cells <- data.frame(z    = c(0, 0, 1, 1, 1, 1),
                    w    = c(0, 0, 0, 0, 1, 1),
                    died = c(1, 0, 1, 0, 1, 0),
                    n    = c(74, 11514, 34, 2385, 12, 9663))
df <- cells[rep(seq_len(nrow(cells)), cells$n), c("z", "w", "died")]
df$deaths <- 1000 * df$died          # deaths per 1,000 children

# Means by assignment, then by assignment and receipt
aggregate(cbind(w, deaths) ~ z, data = df, FUN = mean)
aggregate(deaths ~ z + w, data = df, FUN = function(v) c(n = length(v), mean = mean(v)))

# First stage and outcome ITT, with robust standard errors
first <- lm(w ~ z, data = df)
itt   <- lm(deaths ~ z, data = df)
coeftest(itt, vcov = vcovHC(itt, type = "HC1"))
coef(itt)["z"] / coef(first)["z"]                  # the Wald ratio

# Two-stage least squares gives the Wald ratio with its standard error
iv <- ivreg(deaths ~ w | z, data = df)
coeftest(iv, vcov = vcovHC(iv, type = "HC0"))
coefci(iv, vcov = vcovHC(iv, type = "HC0"), df = Inf)

# The as-treated comparison, for contrast
coef(lm(deaths ~ w, data = df))["w"]
