# LATE for training and earnings: the US National Job Corps Study
# Dr Nicky Grant, drnickygrant.com. Needs: install.packages("AER")
suppressPackageStartupMessages(library(AER))   # ivreg(), coeftest(), vcovHC()

# 9,240 young people. assignment = 1 if placed in the Job Corps (program) group;
# trainy1 = 1 if in education or vocational training in the first year;
# earny4 = weekly earnings (US dollars) in the fourth year after assignment
jc <- read.csv("https://www.drnickygrant.com/teaching/data/job-corps-jc.csv")
# (the same data: data(JC, package = "causalweight"))

# 1. Means by assignment, the two ITTs and their ratio
aggregate(cbind(trainy1, earny4, female) ~ assignment, data = jc, FUN = mean)
first <- lm(trainy1 ~ assignment, data = jc)
itt   <- lm(earny4 ~ assignment, data = jc)
coef(itt)["assignment"] / coef(first)["assignment"]      # the Wald ratio

# 2. Two-stage least squares, without and with a dummy for women
iv  <- ivreg(earny4 ~ trainy1 | assignment, data = jc)
ivf <- ivreg(earny4 ~ trainy1 + female | assignment + female, data = jc)
coeftest(iv,  vcov = vcovHC(iv,  type = "HC0"))
coeftest(ivf, vcov = vcovHC(ivf, type = "HC0"))

# 3. The Wald ratio separately for men and for women
for (f in 0:1) {
  d  <- subset(jc, female == f)
  fs <- diff(tapply(d$trainy1, d$assignment, mean))
  it <- diff(tapply(d$earny4,  d$assignment, mean))
  cat("female =", f, " n =", nrow(d), " first stage", round(fs, 4),
      " ITT", round(it, 4), " Wald", round(it / fs, 4), "\n")
}

# 4. Adding the other characteristics measured at assignment
ivx <- ivreg(earny4 ~ trainy1 + female + age + black + hispanic + hsdegree + everwkd |
             assignment + female + age + black + hispanic + hsdegree + everwkd, data = jc)
round(coeftest(ivx, vcov = vcovHC(ivx, type = "HC0"))["trainy1", ], 4)

# 5. OLS of earnings on training, for contrast
ols <- lm(earny4 ~ trainy1 + female, data = jc)
round(coeftest(ols, vcov = vcovHC(ols, type = "HC1"))["trainy1", ], 4)
