## ---- 3. run -----------------------------------------------------------------
t0  <- Sys.time()
res <- Map(run_one, SPECS$y, SPECS$vce, SPECS$lname)
names(res) <- with(SPECS, paste(y, vce, lname, sep = "_"))
cat(sprintf("\nelapsed: %.1f min\n",
as.numeric(difftime(Sys.time(), t0, units = "mins"))))
bd <- do.call(rbind, lapply(res, function(r) data.frame(
outcome = OUTCOMES[[r$outcome]], vce = r$vce, target = LVECS[[r$lname]]$lab,
orig_lb = r$original$lb, orig_ub = r$original$ub,
bd_RM = r$bd_rm, bd_SD = r$bd_sd, max_pre_2nd_diff = r$max_sd,
row.names = NULL)))
print(bd, digits = 3)
write.csv(bd, file.path(OUT, sprintf("breakdown_summary_ref%d.csv", KREF)),
row.names = FALSE)
## ---- 4. LaTeX table ---------------------------------------------------------
## Rows come from the bracketing path, so the M values are not on a round grid.
## Re-evaluate at the display values you want to print.
fmt <- function(lb, ub) sprintf("[%.2f, %.2f]", lb, ub)
RM_SHOW <- c(0, 0.5, 1, 1.5, 2)
key_par <- paste("tpart", HEADLINE_VCE, HEADLINE_L, sep = "_")
key_for <- paste("tform", HEADLINE_VCE, HEADLINE_L, sep = "_")
show_row <- function(y, m, type) {
inp <- read_inputs(y, HEADLINE_VCE)
ci  <- ci_at(inp, LVECS[[HEADLINE_L]]$l, m, type)
fmt(ci["lb"], ci["ub"])
}
cat("\nevaluating display rows...\n")
rm_par <- sapply(RM_SHOW, function(m) show_row("tpart", m, "rm"))
rm_for <- sapply(RM_SHOW, function(m) show_row("tform", m, "rm"))
r_par <- res[[key_par]]; r_for <- res[[key_for]]
tex <- c(
"\\begin{table}[htbp]",
"\\centering",
"\\caption{Sensitivity to violations of parallel cohort profiles (Rambachan and Roth, 2023)}",
"\\label{tab:honestdid}",
"\\begin{tabular}{lcc}",
"\\hline\\hline",
" & (1) & (2) \\\\",
" & Participation rate & Formality rate \\\\",
"\\hline",
"\\multicolumn{3}{l}{\\textit{Relative magnitudes, $\\Delta^{RM}(\\bar{M})$}} \\\\",
sprintf("$\\bar{M} = %.1f$ & %s & %s \\\\", RM_SHOW, rm_par, rm_for),
sprintf("Breakdown $\\bar{M}$ & %.2f & %.2f \\\\", r_par$bd_rm, r_for$bd_rm),
"\\hline",
sprintf("Original 95\\%% CI & %s & %s \\\\",
fmt(r_par$original$lb, r_par$original$ub),
fmt(r_for$original$lb, r_for$original$ub)),
"\\hline\\hline",
"\\end{tabular}",
"\\end{table}")
writeLines(tex, file.path(OUT, sprintf("table_honestdid_ref%d.tex", KREF)))
cat(tex, sep = "\n")
## ---- 5. figures -------------------------------------------------------------
plot_one <- function(r, which) {
d <- r[[which]]
o <- data.frame(M = min(d$M) - diff(range(d$M)) / 12,
lb = r$original$lb, ub = r$original$ub, kind = "Original")
d <- data.frame(M = d$M, lb = d$lb, ub = d$ub, kind = "Robust")
ggplot(rbind(o, d), aes(M, ymin = lb, ymax = ub, colour = kind)) +
geom_errorbar(width = 0) + geom_hline(yintercept = 0, linetype = 2) +
labs(x = if (which == "rm") expression(bar(M)) else "M",
y = "95% CI", colour = NULL,
title = sprintf("%s (%s, ref %d)", OUTCOMES[[r$outcome]], r$vce, KREF)) +
theme_minimal(base_size = 11) + theme(legend.position = "bottom")
}
for (k in c(key_par, key_for)) {
ggsave(file.path(OUT, sprintf("fig_rm_%s_ref%d.pdf", res[[k]]$outcome, KREF)),
plot_one(res[[k]], "rm"), width = 5.5, height = 4)
}
## =============================================================================
## =============================================================================
## E__HonestDiD_CohortSpace_fast.R
##
## Replaces the dense-grid version. Two changes:
##   (1) breakdown values are found by coarse bracketing + bisection
##       (~15 evaluations instead of 121);
##   (2) the factorial is cut to the specifications actually reported.
##
## Rough cost: the old script asked for ~1,900 relative-magnitudes problems.
## This one asks for ~150.
## =============================================================================
library(HonestDiD)
library(ggplot2)
setwd("/Users/alainpineda/Library/CloudStorage/GoogleDrive-alainpp25@gmail.com/My Drive/PhD/Projects/Tienes IMSS/Update26")
OUT <- "ThemeE"
## ---- 0. configuration -------------------------------------------------------
COHORTS <- 1991:2004
KREF    <- 1997L                  # 1998 is partially treated via public college
OUTCOMES <- c(tform = "Formality rate", tpart = "Participation rate")
## Only what goes in the paper. Add rows to widen.
SPECS <- rbind(
data.frame(y = "tform", vce = "CV3",  lname = "full2"),
data.frame(y = "tform", vce = "CV3",  lname = "full"),
data.frame(y = "tform", vce = "CRV1", lname = "full2"),
data.frame(y = "tpart", vce = "CV3",  lname = "full2"),
data.frame(y = "tpart", vce = "CV3",  lname = "full"),
data.frame(y = "tpart", vce = "CRV1", lname = "full2"),
stringsAsFactors = FALSE)
HEADLINE_VCE <- "CV3"
HEADLINE_L   <- "full2"           # 2001-02: fully exposed, observed at 14-18
## Speed knobs for the ARP grid search. Defaults are gridPoints = 1000 and an
## automatically chosen grid; tightening both is where most of the saving is.
## Check ?createSensitivityResults_relativeMagnitudes if an argument errors --
## names have changed across versions.
GRIDPTS <- 1000L
GRID_LB <- -4
GRID_UB <-  4
exposure <- function(k) ifelse(k <= 1998, 0,
ifelse(k == 1999, 1/3,
ifelse(k == 2000, 2/3, 1)))
## ---- 1. normalisation and target vectors ------------------------------------
evlist <- setdiff(COHORTS, KREF)
pre_k  <- evlist[evlist < KREF]
post_k <- evlist[evlist > KREF]
NPRE   <- length(pre_k)
NPOST  <- length(post_k)
A <- matrix(0, nrow = length(evlist), ncol = length(COHORTS))
for (i in seq_along(evlist)) {
A[i, match(evlist[i], COHORTS)] <- 1
A[i, match(KREF,      COHORTS)] <- -1
}
expo <- exposure(post_k)
LVECS <- list(
full  = list(l = as.numeric(expo == 1) / sum(expo == 1),
lab = "Fully exposed cohorts (2001--2004)"),
full2 = list(l = as.numeric(post_k %in% 2001:2002) / sum(post_k %in% 2001:2002),
lab = "Fully exposed, working-age window (2001--2002)"),
proj  = list(l = expo / sum(expo^2),
lab = "Per unit of full exposure"),
first = list(l = as.numeric(post_k == min(post_k)),
lab = sprintf("First post-reference cohort (%d)", min(post_k))))
cat(sprintf("Reference cohort %d: %d pre-periods, %d post-periods\n",
KREF, NPRE, NPOST))
## Targets actually used must put zero weight on unexposed cohorts.
## `first` is exempt by design: with KREF < 1998 it points at an unexposed
## cohort and measures the college-contamination uptick, not an effect.
used <- unique(SPECS$lname)
chk  <- sapply(LVECS[used], function(z) abs(sum(z$l[expo == 0])))
if (any(chk > 1e-12))
stop("target(s) place weight on unexposed cohorts: ",
paste(used[chk > 1e-12], collapse = ", "))
## ---- 2. helpers -------------------------------------------------------------
read_inputs <- function(y, vce) {
b14 <- as.numeric(unlist(read.csv(file.path(OUT, sprintf("beta14_%s_%s.csv", y, vce)))))
V14 <- as.matrix(read.csv(file.path(OUT, sprintf("sigma14_%s_%s.csv", y, vce))))
dimnames(V14) <- NULL
stopifnot(length(b14) == length(COHORTS), all(dim(V14) == length(COHORTS)))
S <- A %*% V14 %*% t(A)
list(betahat = as.numeric(A %*% b14), sigma = (S + t(S)) / 2)
}
## one CI at a single M (or Mbar)
ci_at <- function(inp, l, m, type) {
if (type == "rm") {
r <- createSensitivityResults_relativeMagnitudes(
betahat = inp$betahat, sigma = inp$sigma,
numPrePeriods = NPRE, numPostPeriods = NPOST,
Mbarvec = m, l_vec = l,
gridPoints = GRIDPTS, grid.lb = GRID_LB, grid.ub = GRID_UB)
} else {
r <- createSensitivityResults(
betahat = inp$betahat, sigma = inp$sigma,
numPrePeriods = NPRE, numPostPeriods = NPOST,
Mvec = m, l_vec = l)
}
c(lb = unname(r$lb[1]), ub = unname(r$ub[1]))
}
## coarse bracket, then bisect to tol
find_breakdown <- function(inp, l, type, coarse, tol, label) {
covers <- function(ci) ci["lb"] <= 0 & ci["ub"] >= 0
tab <- NULL
lo <- NA; hi <- NA
for (m in coarse) {
ci <- ci_at(inp, l, m, type)
tab <- rbind(tab, data.frame(M = m, lb = ci["lb"], ub = ci["ub"]))
cat(sprintf("  [%s/%s] M = %7.4f  CI = [%7.3f, %7.3f]\n",
label, type, m, ci["lb"], ci["ub"]))
if (covers(ci)) { hi <- m; break } else lo <- m
}
if (is.na(hi)) { cat("  no breakdown on the coarse grid\n")
return(list(bd = NA_real_, tab = tab)) }
if (is.na(lo)) { cat("  breaks down at the first grid point\n")
return(list(bd = coarse[1], tab = tab)) }
while (hi - lo > tol) {
mid <- (lo + hi) / 2
ci  <- ci_at(inp, l, mid, type)
tab <- rbind(tab, data.frame(M = mid, lb = ci["lb"], ub = ci["ub"]))
cat(sprintf("  [%s/%s] bisect %7.4f  CI = [%7.3f, %7.3f]\n",
label, type, mid, ci["lb"], ci["ub"]))
if (covers(ci)) hi <- mid else lo <- mid
}
list(bd = (lo + hi) / 2, tab = tab[order(tab$M), ])
}
run_one <- function(y, vce, lname) {
label <- paste(y, vce, lname, sep = "/")
cat(sprintf("\n=== %s ===\n", label))
inp <- read_inputs(y, vce)
l   <- LVECS[[lname]]$l
orig <- constructOriginalCS(betahat = inp$betahat, sigma = inp$sigma,
numPrePeriods = NPRE, numPostPeriods = NPOST,
l_vec = l)
cat(sprintf("  original CI = [%7.3f, %7.3f]\n", orig$lb, orig$ub))
rm_bd <- find_breakdown(inp, l, "rm",
coarse = c(0, 0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4),
tol = 0.02, label = label)
pre_path <- c(inp$betahat[seq_len(NPRE)], 0)
max_sd   <- max(abs(diff(pre_path, differences = 2)))
sd_bd <- find_breakdown(inp, l, "sd",
coarse = max_sd * c(0, 0.05, 0.1, 0.25, 0.5, 1, 2),
tol = max_sd / 200, label = label)
list(outcome = y, vce = vce, lname = lname, original = orig,
rm = rm_bd$tab, sd = sd_bd$tab, max_sd = max_sd,
bd_rm = rm_bd$bd, bd_sd = sd_bd$bd)
}
## ---- 3. run -----------------------------------------------------------------
t0  <- Sys.time()
res <- Map(run_one, SPECS$y, SPECS$vce, SPECS$lname)
names(res) <- with(SPECS, paste(y, vce, lname, sep = "_"))
cat(sprintf("\nelapsed: %.1f min\n",
as.numeric(difftime(Sys.time(), t0, units = "mins"))))
bd <- do.call(rbind, lapply(res, function(r) data.frame(
outcome = OUTCOMES[[r$outcome]], vce = r$vce, target = LVECS[[r$lname]]$lab,
orig_lb = r$original$lb, orig_ub = r$original$ub,
bd_RM = r$bd_rm, bd_SD = r$bd_sd, max_pre_2nd_diff = r$max_sd,
row.names = NULL)))
print(bd, digits = 3)
write.csv(bd, file.path(OUT, sprintf("breakdown_summary_ref%d.csv", KREF)),
row.names = FALSE)
## ---- 4. LaTeX table ---------------------------------------------------------
## Rows come from the bracketing path, so the M values are not on a round grid.
## Re-evaluate at the display values you want to print.
fmt <- function(lb, ub) sprintf("[%.2f, %.2f]", lb, ub)
RM_SHOW <- c(0, 0.5, 1, 1.5, 2)
key_par <- paste("tpart", HEADLINE_VCE, HEADLINE_L, sep = "_")
key_for <- paste("tform", HEADLINE_VCE, HEADLINE_L, sep = "_")
show_row <- function(y, m, type) {
inp <- read_inputs(y, HEADLINE_VCE)
ci  <- ci_at(inp, LVECS[[HEADLINE_L]]$l, m, type)
fmt(ci["lb"], ci["ub"])
}
cat("\nevaluating display rows...\n")
rm_par <- sapply(RM_SHOW, function(m) show_row("tpart", m, "rm"))
rm_for <- sapply(RM_SHOW, function(m) show_row("tform", m, "rm"))
r_par <- res[[key_par]]; r_for <- res[[key_for]]
tex <- c(
"\\begin{table}[htbp]",
"\\centering",
"\\caption{Sensitivity to violations of parallel cohort profiles (Rambachan and Roth, 2023)}",
"\\label{tab:honestdid}",
"\\begin{tabular}{lcc}",
"\\hline\\hline",
" & (1) & (2) \\\\",
" & Participation rate & Formality rate \\\\",
"\\hline",
"\\multicolumn{3}{l}{\\textit{Relative magnitudes, $\\Delta^{RM}(\\bar{M})$}} \\\\",
sprintf("$\\bar{M} = %.1f$ & %s & %s \\\\", RM_SHOW, rm_par, rm_for),
sprintf("Breakdown $\\bar{M}$ & %.2f & %.2f \\\\", r_par$bd_rm, r_for$bd_rm),
"\\hline",
sprintf("Original 95\\%% CI & %s & %s \\\\",
fmt(r_par$original$lb, r_par$original$ub),
fmt(r_for$original$lb, r_for$original$ub)),
"\\hline\\hline",
"\\end{tabular}",
"\\end{table}")
writeLines(tex, file.path(OUT, sprintf("table_honestdid_ref%d.tex", KREF)))
cat(tex, sep = "\n")
## ---- 5. figures -------------------------------------------------------------
## The stored rm/sd tables come from the bracketing path, so their M values are
## irregular and bunch up where bisection converged. Re-evaluate on a regular
## grid for the figure only.
plot_one <- function(r, which = "rm", mgrid = seq(0, 2, by = 0.25)) {
inp <- read_inputs(r$outcome, r$vce)
l   <- LVECS[[r$lname]]$l
bd  <- if (which == "rm") r$bd_rm else r$bd_sd
d <- do.call(rbind, lapply(mgrid, function(m) {
ci <- ci_at(inp, l, m, which)
data.frame(M = m, lb = ci["lb"], ub = ci["ub"], kind = "Robust",
row.names = NULL)
}))
o <- data.frame(M = min(mgrid) - diff(range(mgrid)) / 12,
lb = r$original$lb, ub = r$original$ub, kind = "Original",
row.names = NULL)
ggplot(rbind(o, d), aes(M, ymin = lb, ymax = ub, colour = kind)) +
geom_errorbar(width = 0) +
geom_hline(yintercept = 0, linetype = 2) +
geom_vline(xintercept = bd, linetype = 3, colour = "grey40") +
scale_x_continuous(breaks = mgrid) +
labs(x = if (which == "rm") expression(bar(M)) else "M",
y = "95% CI", colour = NULL,
title = sprintf("%s (%s, ref %d)", OUTCOMES[[r$outcome]], r$vce, KREF)) +
theme_minimal(base_size = 11) + theme(legend.position = "bottom")
}
for (k in c(key_par, key_for)) {
ggsave(file.path(OUT, sprintf("fig_rm_%s_ref%d.pdf", res[[k]]$outcome, KREF)),
plot_one(res[[k]], "rm"), width = 5.5, height = 4)
}
## =============================================================================
res[["tform_CV3_full2"]]$sd
res[["tpart_CV3_full2"]]$sd
library(HonestDiD)
## =============================================================================
## E__HonestDiD_CohortSpace_fast.R
##
## Replaces the dense-grid version. Two changes:
##   (1) breakdown values are found by coarse bracketing + bisection
##       (~15 evaluations instead of 121);
##   (2) the factorial is cut to the specifications actually reported.
##
## Rough cost: the old script asked for ~1,900 relative-magnitudes problems.
## This one asks for ~150.
## =============================================================================
library(HonestDiD)
library(ggplot2)
setwd("/Users/alainpineda/Library/CloudStorage/GoogleDrive-alainpp25@gmail.com/My Drive/PhD/Projects/Tienes IMSS/replication/output")
OUT <- "ThemeE"
## ---- 0. configuration -------------------------------------------------------
COHORTS <- 1991:2004
KREF    <- 1997L                  # 1998 is partially treated via public college
OUTCOMES <- c(tform = "Formality rate", tpart = "Participation rate")
## Only what goes in the paper. Add rows to widen.
SPECS <- rbind(
data.frame(y = "tform", vce = "CV3",  lname = "full2"),
data.frame(y = "tform", vce = "CV3",  lname = "full"),
data.frame(y = "tform", vce = "CRV1", lname = "full2"),
data.frame(y = "tpart", vce = "CV3",  lname = "full2"),
data.frame(y = "tpart", vce = "CV3",  lname = "full"),
data.frame(y = "tpart", vce = "CRV1", lname = "full2"),
stringsAsFactors = FALSE)
HEADLINE_VCE <- "CV3"
HEADLINE_L   <- "full2"           # 2001-02: fully exposed, observed at 14-18
## Speed knobs for the ARP grid search. Defaults are gridPoints = 1000 and an
## automatically chosen grid; tightening both is where most of the saving is.
## Check ?createSensitivityResults_relativeMagnitudes if an argument errors --
## names have changed across versions.
GRIDPTS <- 300L
GRID_LB <- -8
GRID_UB <-  8
exposure <- function(k) ifelse(k <= 1998, 0,
ifelse(k == 1999, 1/3,
ifelse(k == 2000, 2/3, 1)))
## ---- 1. normalisation and target vectors ------------------------------------
evlist <- setdiff(COHORTS, KREF)
pre_k  <- evlist[evlist < KREF]
post_k <- evlist[evlist > KREF]
NPRE   <- length(pre_k)
NPOST  <- length(post_k)
A <- matrix(0, nrow = length(evlist), ncol = length(COHORTS))
for (i in seq_along(evlist)) {
A[i, match(evlist[i], COHORTS)] <- 1
A[i, match(KREF,      COHORTS)] <- -1
}
expo <- exposure(post_k)
LVECS <- list(
full  = list(l = as.numeric(expo == 1) / sum(expo == 1),
lab = "Fully exposed cohorts (2001--2004)"),
full2 = list(l = as.numeric(post_k %in% 2001:2002) / sum(post_k %in% 2001:2002),
lab = "Fully exposed, working-age window (2001--2002)"),
proj  = list(l = expo / sum(expo^2),
lab = "Per unit of full exposure"),
first = list(l = as.numeric(post_k == min(post_k)),
lab = sprintf("First post-reference cohort (%d)", min(post_k))))
cat(sprintf("Reference cohort %d: %d pre-periods, %d post-periods\n",
KREF, NPRE, NPOST))
## Targets actually used must put zero weight on unexposed cohorts.
## `first` is exempt by design: with KREF < 1998 it points at an unexposed
## cohort and measures the college-contamination uptick, not an effect.
used <- unique(SPECS$lname)
chk  <- sapply(LVECS[used], function(z) abs(sum(z$l[expo == 0])))
if (any(chk > 1e-12))
stop("target(s) place weight on unexposed cohorts: ",
paste(used[chk > 1e-12], collapse = ", "))
## ---- 2. helpers -------------------------------------------------------------
read_inputs <- function(y, vce) {
b14 <- as.numeric(unlist(read.csv(file.path(OUT, sprintf("beta14_%s_%s.csv", y, vce)))))
V14 <- as.matrix(read.csv(file.path(OUT, sprintf("sigma14_%s_%s.csv", y, vce))))
dimnames(V14) <- NULL
stopifnot(length(b14) == length(COHORTS), all(dim(V14) == length(COHORTS)))
S <- A %*% V14 %*% t(A)
list(betahat = as.numeric(A %*% b14), sigma = (S + t(S)) / 2)
}
## one CI at a single M (or Mbar)
ci_at <- function(inp, l, m, type) {
if (type == "rm") {
r <- createSensitivityResults_relativeMagnitudes(
betahat = inp$betahat, sigma = inp$sigma,
numPrePeriods = NPRE, numPostPeriods = NPOST,
Mbarvec = m, l_vec = l,
gridPoints = GRIDPTS, grid.lb = GRID_LB, grid.ub = GRID_UB)
} else {
r <- createSensitivityResults(
betahat = inp$betahat, sigma = inp$sigma,
numPrePeriods = NPRE, numPostPeriods = NPOST,
Mvec = m, l_vec = l)
}
c(lb = unname(r$lb[1]), ub = unname(r$ub[1]))
}
## coarse bracket, then bisect to tol
find_breakdown <- function(inp, l, type, coarse, tol, label) {
covers <- function(ci) ci["lb"] <= 0 & ci["ub"] >= 0
tab <- NULL
lo <- NA; hi <- NA
for (m in coarse) {
ci <- ci_at(inp, l, m, type)
tab <- rbind(tab, data.frame(M = m, lb = ci["lb"], ub = ci["ub"]))
cat(sprintf("  [%s/%s] M = %7.4f  CI = [%7.3f, %7.3f]\n",
label, type, m, ci["lb"], ci["ub"]))
if (covers(ci)) { hi <- m; break } else lo <- m
}
if (is.na(hi)) { cat("  no breakdown on the coarse grid\n")
return(list(bd = NA_real_, tab = tab)) }
if (is.na(lo)) { cat("  breaks down at the first grid point\n")
return(list(bd = coarse[1], tab = tab)) }
while (hi - lo > tol) {
mid <- (lo + hi) / 2
ci  <- ci_at(inp, l, mid, type)
tab <- rbind(tab, data.frame(M = mid, lb = ci["lb"], ub = ci["ub"]))
cat(sprintf("  [%s/%s] bisect %7.4f  CI = [%7.3f, %7.3f]\n",
label, type, mid, ci["lb"], ci["ub"]))
if (covers(ci)) hi <- mid else lo <- mid
}
list(bd = (lo + hi) / 2, tab = tab[order(tab$M), ])
}
run_one <- function(y, vce, lname) {
label <- paste(y, vce, lname, sep = "/")
cat(sprintf("\n=== %s ===\n", label))
inp <- read_inputs(y, vce)
l   <- LVECS[[lname]]$l
orig <- constructOriginalCS(betahat = inp$betahat, sigma = inp$sigma,
numPrePeriods = NPRE, numPostPeriods = NPOST,
l_vec = l)
cat(sprintf("  original CI = [%7.3f, %7.3f]\n", orig$lb, orig$ub))
rm_bd <- find_breakdown(inp, l, "rm",
coarse = c(0, 0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4),
tol = 0.02, label = label)
pre_path <- c(inp$betahat[seq_len(NPRE)], 0)
max_sd   <- max(abs(diff(pre_path, differences = 2)))
sd_bd <- find_breakdown(inp, l, "sd",
coarse = max_sd * c(0, 0.05, 0.1, 0.25, 0.5, 1, 2),
tol = max_sd / 200, label = label)
list(outcome = y, vce = vce, lname = lname, original = orig,
rm = rm_bd$tab, sd = sd_bd$tab, max_sd = max_sd,
bd_rm = rm_bd$bd, bd_sd = sd_bd$bd)
}
## ---- 3. run -----------------------------------------------------------------
t0  <- Sys.time()
res <- Map(run_one, SPECS$y, SPECS$vce, SPECS$lname)
names(res) <- with(SPECS, paste(y, vce, lname, sep = "_"))
cat(sprintf("\nelapsed: %.1f min\n",
as.numeric(difftime(Sys.time(), t0, units = "mins"))))
bd <- do.call(rbind, lapply(res, function(r) data.frame(
outcome = OUTCOMES[[r$outcome]], vce = r$vce, target = LVECS[[r$lname]]$lab,
orig_lb = r$original$lb, orig_ub = r$original$ub,
bd_RM = r$bd_rm, bd_SD = r$bd_sd, max_pre_2nd_diff = r$max_sd,
row.names = NULL)))
print(bd, digits = 3)
write.csv(bd, file.path(OUT, sprintf("breakdown_summary_ref%d.csv", KREF)),
row.names = FALSE)
## ---- 4. LaTeX table ---------------------------------------------------------
## Rows come from the bracketing path, so the M values are not on a round grid.
## Re-evaluate at the display values you want to print.
fmt <- function(lb, ub) sprintf("[%.2f, %.2f]", lb, ub)
RM_SHOW <- c(0, 0.5, 1, 1.5, 2)
key_par <- paste("tpart", HEADLINE_VCE, HEADLINE_L, sep = "_")
key_for <- paste("tform", HEADLINE_VCE, HEADLINE_L, sep = "_")
show_row <- function(y, m, type) {
inp <- read_inputs(y, HEADLINE_VCE)
ci  <- ci_at(inp, LVECS[[HEADLINE_L]]$l, m, type)
fmt(ci["lb"], ci["ub"])
}
cat("\nevaluating display rows...\n")
rm_par <- sapply(RM_SHOW, function(m) show_row("tpart", m, "rm"))
rm_for <- sapply(RM_SHOW, function(m) show_row("tform", m, "rm"))
r_par <- res[[key_par]]; r_for <- res[[key_for]]
tex <- c(
"\\begin{table}[htbp]",
"\\centering",
"\\caption{Sensitivity to violations of parallel cohort profiles (Rambachan and Roth, 2023)}",
"\\label{tab:honestdid}",
"\\begin{tabular}{lcc}",
"\\hline\\hline",
" & (1) & (2) \\\\",
" & Participation rate & Formality rate \\\\",
"\\hline",
"\\multicolumn{3}{l}{\\textit{Relative magnitudes, $\\Delta^{RM}(\\bar{M})$}} \\\\",
sprintf("$\\bar{M} = %.1f$ & %s & %s \\\\", RM_SHOW, rm_par, rm_for),
sprintf("Breakdown $\\bar{M}$ & %.2f & %.2f \\\\", r_par$bd_rm, r_for$bd_rm),
"\\hline",
sprintf("Original 95\\%% CI & %s & %s \\\\",
fmt(r_par$original$lb, r_par$original$ub),
fmt(r_for$original$lb, r_for$original$ub)),
"\\hline\\hline",
"\\end{tabular}",
"\\end{table}")
writeLines(tex, file.path(OUT, sprintf("table_honestdid_ref%d.tex", KREF)))
cat(tex, sep = "\n")
## ---- 5. figures -------------------------------------------------------------
plot_one <- function(r, which) {
d <- r[[which]]
o <- data.frame(M = min(d$M) - diff(range(d$M)) / 12,
lb = r$original$lb, ub = r$original$ub, kind = "Original")
d <- data.frame(M = d$M, lb = d$lb, ub = d$ub, kind = "Robust")
ggplot(rbind(o, d), aes(M, ymin = lb, ymax = ub, colour = kind)) +
geom_errorbar(width = 0) + geom_hline(yintercept = 0, linetype = 2) +
labs(x = if (which == "rm") expression(bar(M)) else "M",
y = "95% CI", colour = NULL,
title = sprintf("%s (%s, ref %d)", OUTCOMES[[r$outcome]], r$vce, KREF)) +
theme_minimal(base_size = 11) + theme(legend.position = "bottom")
}
for (k in c(key_par, key_for)) {
ggsave(file.path(OUT, sprintf("fig_rm_%s_ref%d.pdf", res[[k]]$outcome, KREF)),
plot_one(res[[k]], "rm"), width = 5.5, height = 4)
}
## =============================================================================
