/
print.R
463 lines (385 loc) · 19.4 KB
/
print.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
# prints, summaries and reports -------------------------------------------
#' Sensitivity analysis print and summary methods for \code{sensemakr}
#'
#' @description
#' The \code{print} and \code{summary} methods provide verbal descriptions of the sensitivity analysis results
#' obtained with the function \code{\link{sensemakr}}. The function \code{\link{ovb_minimal_reporting}} provides
#' latex or html code for a minimal
#' sensitivity analysis reporting, as suggested in Cinelli and Hazlett (2020).
#'
#' @param ... arguments passed to other methods.
#' @param x an object of class \code{\link{sensemakr}}.
#' @param digits minimal number of \emph{significant} digits.
#'
#' @examples
#' # runs regression model
#' model <- lm(peacefactor ~ directlyharmed + age + farmer_dar + herder_dar +
#' pastvoted + hhsize_darfur + female + village,
#' data = darfur)
#'
#' # runs sensemakr for sensitivity analysis
#' sensitivity <- sensemakr(model, treatment = "directlyharmed",
#' benchmark_covariates = "female",
#' kd = 1:3)
#' # print
#' sensitivity
#'
#' # summary
#' summary(sensitivity)
#'
#' # prints latex code for minimal sensitivity analysis reporting
#' ovb_minimal_reporting(sensitivity)
#'
#' @references Cinelli, C. and Hazlett, C. (2020), "Making Sense of Sensitivity: Extending Omitted Variable Bias." Journal of the Royal Statistical Society, Series B (Statistical Methodology).
#'
#' @export
print.sensemakr = function(x,
digits = max(3L, getOption("digits") - 2L),
...
) {
cat("Sensitivity Analysis to Unobserved Confounding\n\n")
cat("Model Formula: ", paste(deparse(x$info$formula),
sep = "\n", collapse = "\n"),
"\n\n", sep = "")
reduce <- x$info$reduce
q <- x$info$q
cat("Null hypothesis:", "q =", q, "and", "reduce =", reduce,"\n\n")
cat("Unadjusted Estimates of '", treatment <- x$sensitivity_stats$treatment, "':\n ")
cat(" Coef. estimate:", estimate <- round(x$sensitivity_stats$estimate, digits), "\n ")
cat(" Standard Error:", se <- round(x$sensitivity_stats$se, digits), "\n ")
cat(" t-value:", t_statistic <- round(x$sensitivity_stats$t_statistic, digits), "\n")
cat("\n")
cat("Sensitivity Statistics:\n ")
cat(" Partial R2 of treatment with outcome:", r2yd.x <- round(x$sensitivity_stats$r2yd.x,digits), "\n ")
cat(" Robustness Value,", "q =", q <- x$info$q, ":", rv_q <- round(x$sensitivity_stats$rv_q,digits), "\n ")
cat(" Robustness Value,", "q =", q, "alpha =", alpha <- x$info$alpha, ":", rv_qa <- round(x$sensitivity_stats$rv_qa,digits), "\n")
cat("\n")
cat("For more information, check summary.")
}
.simpleCap <- function(x) {
s <- strsplit(x, " ")[[1]]
paste(toupper(substring(s, 1, 1)), substring(s, 2),
sep = "", collapse = " ")
}
#' @rdname print.sensemakr
#' @param object an object of class \code{\link{sensemakr}}.
#' @export
summary.sensemakr <- function(object, digits = max(3L, getOption("digits") - 3L), ...){
x <- object
q <- x$info$q
alpha <- x$info$alpha
reduce <- x$info$reduce
h0 <- round(ifelse(reduce, x$sensitivity_stats$estimate*(1 - q), x$sensitivity_stats$estimate*(1 + q)), 4)
direction <- ifelse(reduce, "reduce", "increase")
cat("Sensitivity Analysis to Unobserved Confounding\n\n")
cat("Model Formula: ", paste(deparse(x$info$formula),
sep = "\n", collapse = "\n"),
"\n\n", sep = "")
cat("Null hypothesis:", "q =", q, "and", "reduce =", reduce,"\n")
cat("-- This means we are considering biases that", direction, "the absolute value of the current estimate.\n")
cat("-- The null hypothesis deemed problematic is H0:tau =", h0, "\n")
cat("\n")
cat("Unadjusted Estimates of", paste0("'",treatment <- x$sensitivity_stats$treatment,"':"), "\n ")
cat(" Coef. estimate:", estimate <- round(x$sensitivity_stats$estimate, digits), "\n ")
cat(" Standard Error:", se <- round(x$sensitivity_stats$se, digits), "\n ")
cat(" t-value", "(H0:tau =", paste0(h0,"):"), t_statistic <- round(x$sensitivity_stats$t_statistic, digits), "\n")
cat("\n")
cat("Sensitivity Statistics:\n ")
cat(" Partial R2 of treatment with outcome:", r2yd.x <- round(x$sensitivity_stats$r2yd.x,digits), "\n ")
cat(" Robustness Value,", "q =", paste0(q, ":"), rv_q <- round(x$sensitivity_stats$rv_q,digits), "\n ")
cat(" Robustness Value,", "q =", paste0(q, ","), "alpha =", paste0(alpha, ":"), rv_qa <- round(x$sensitivity_stats$rv_qa,digits), "\n")
cat("\n")
reduce <- ifelse(x$info$reduce, "reduce", "increase")
cat("Verbal interpretation of sensitivity statistics:\n\n")
cat("-- Partial R2 of the treatment with the outcome: an extreme confounder (orthogonal to the covariates) that explains 100% of the residual variance of the outcome, would need to explain at least",
paste0(100*r2yd.x, "%"),"of the residual variance of the treatment to fully account for the observed estimated effect.")
cat("\n\n")
cat("-- Robustness Value,", "q =", paste0(q, ":"), "unobserved confounders (orthogonal to the covariates) that explain more than",
paste0(100*rv_q,"%"), "of the residual variance",
"of both the treatment and the outcome are strong enough to bring the point estimate to", paste0(h0),
"(a bias of", paste0(100*q, "%"),"of the original estimate).",
"Conversely, unobserved confounders that do not explain more than", paste0(100*rv_q,"%"), "of the residual variance",
"of both the treatment and the outcome are not strong enough to bring the point estimate to", paste0(h0,"."))
cat("\n\n")
cat("-- Robustness Value,", "q =", paste0(q, ","), "alpha =", paste0(alpha, ":"), "unobserved confounders (orthogonal to the covariates) that explain more than", paste0(100*rv_qa,"%"), "of the residual variance",
"of both the treatment and the outcome are strong enough to bring the estimate to a range where it is no longer 'statistically different' from",
paste0(h0), "(a bias of", paste0(100*q, "%"),"of the original estimate),",
"at the significance level of alpha =", paste0(alpha, "."),
"Conversely, unobserved confounders that do not explain more than", paste0(100*rv_qa,"%"), "of the residual variance",
"of both the treatment and the outcome are not strong enough to bring the estimate to a range where it is no longer 'statistically different' from",
paste0(h0,","),
"at the significance level of alpha =", paste0(alpha,"."))
cat("\n\n")
bounds <- x$bounds
if (!is.null(bounds)) {
numeric <- sapply(bounds, is.numeric)
bounds[numeric] <- lapply(bounds[numeric], round, digits = digits)
names(bounds) <- sapply(gsub("\\_", " ", names(bounds)), .simpleCap)
cat("Bounds on omitted variable bias:\n\n")
cat("--The table below shows the maximum strength of unobserved confounders with association with the treatment and the outcome bounded by a multiple of the observed explanatory power of the chosen benchmark covariate(s).\n\n")
print(bounds, row.names = FALSE)
}
}
#' @rdname print.sensemakr
#' @return
#' The function \code{ovb_minimal_reporting} returns the LaTeX/HTML code invisibly in character form and also prints with
#' \code{\link{cat}} the LaTeX code. To suppress automatic printing, set \code{verbose = FALSE}.
#' @param format code format to print, either \code{latex} or \code{html}. The default html version
#' has some mathematical content that requires mathjax or equivalent library to parse.
#' If you need only html, use the option "pure_html".
#'
#' @param verbose if `TRUE`, the function prints the LaTeX code with \code{\link{cat}}
#' @export
ovb_minimal_reporting <- function(x, digits = 3, verbose = TRUE, format = c("latex", "html", "pure_html"), ...){
if (!inherits(x, "sensemakr")) stop("Object needs to be of class sensemakr.")
format <- match.arg(format)
fun <- switch(format,
latex = latex_table,
html = html_table,
pure_html = html_table_no_mathjax)
fun(x = x, digits = digits, verbose = verbose, ...)
}
latex_table <- function(x, digits = 3, verbose = TRUE, ...){
# Let's begin
table_settings = list(...)
# Override variable labels
outcome_label = ifelse(is.null(table_settings[["outcome_label"]]),
all.vars(x$info$formula)[1],
table_settings[["outcome_label"]])
treatment_label = ifelse(is.null(table_settings[["treatment_label"]]),
x$sensitivity_stats$treatment,
table_settings["treatment_label"])
# Okay, static beginning
table_begin = paste0("\\begin{table}[!h]\n",
"\\centering\n",
"\\begin{tabular}{lrrrrrr}\n")
# Outcome variable header
outcome_header = sprintf("\\multicolumn{7}{c}{Outcome: \\textit{%s}} \\\\\n",
outcome_label)
# Coeff header row
coeff_header = paste0(
"\\hline \\hline \n",
"Treatment: & Est. & S.E. & t-value & $R^2_{Y \\sim D |{\\bf X}}$ ",
paste0("& $RV_{q = ", x$info$q, "}$ "),
paste0("& $RV_{q = ", x$info$q, ", \\alpha = ", x$info$alpha, "}$ "),
" \\\\ \n",
"\\hline \n"
)
# Treatment result
# Why paste and not sprintf? Easier to handle precision on the digits.
coeff_results = paste0(
"\\textit{", treatment_label, "} & ",
round(x$sensitivity_stats$estimate, digits), " & ",
round(x$sensitivity_stats$se, digits), " & ",
round(x$sensitivity_stats$t_statistic, digits)," & ",
100 * round(x$sensitivity_stats$r2yd.x, digits), "\\% & ",
100 * round(x$sensitivity_stats$rv_q, digits), "\\% & ",
100 * round(x$sensitivity_stats$rv_qa, digits), "\\% \\\\ \n")
# Foonote row: Display benchmarks
if (!is.null(x$bounds)) {
footnote_begin = paste0("\\hline \n",
"df = ", x$sensitivity_stats$dof, " & & ",
"\\multicolumn{5}{r}{ ",
"")
row = x$bounds[1, , drop = FALSE]
footnotes = paste0("\\small ",
"\\textit{Bound (", row$bound_label, ")}: ",
"$R^2_{Y\\sim Z| {\\bf X}, D}$ = ",
100 * round(row$r2yz.dx, digits),
"\\%, $R^2_{D\\sim Z| {\\bf X} }$ = ",
100 * round(row$r2dz.x, digits),
"\\%")
footnote_body = paste0(footnotes, collapse = " \\\\ ")
footnote_end = "} \\\\\n"
footnote = paste0(footnote_begin, footnote_body, footnote_end)
} else {
footnote = paste0("\\hline \n",
"df = ", x$sensitivity_stats$dof, " & & ",
"\\multicolumn{5}{r}{ ",
"}")
}
# Below footnote end table, caption, label
tabular_end = "\\end{tabular}\n"
caption = ifelse(!is.null(table_settings[["caption"]]),
paste0("\\caption{", table_settings[["caption"]], "} \n"),
"")
label = ifelse(!is.null(table_settings[["label"]]),
paste0("\\label{", table_settings[["label"]], "} \n"),
"")
table_end = "\\end{table}"
# Stick it all together
table = paste0(table_begin, outcome_header, coeff_header,
coeff_results, footnote, tabular_end,
caption, label, table_end)
# Cat to output valid LaTeX for rmarkdown
if (verbose) cat(table)
return(invisible(table))
}
html_table <- function(x, digits = 3, verbose = TRUE, ...){
# Let's begin
table_settings = list(...)
outcome_label = ifelse(is.null(table_settings[["outcome_label"]]),
all.vars(x$info$formula)[1],
table_settings[["outcome_label"]])
treatment_label = ifelse(is.null(table_settings[["treatment_label"]]),
x$sensitivity_stats$treatment,
table_settings["treatment_label"])
# Okay, static beginning
table_begin = paste0("<table>\n")
# Coeff header row
coeff_header = paste0(
"<thead>\n",
"<tr>\n",
'\t<th style="text-align:left;border-bottom: 1px solid transparent;border-top: 1px solid black"> </th>\n',
'\t<th colspan = 6 style="text-align:center;border-bottom: 1px solid black;border-top: 1px solid black"> Outcome: ',
outcome_label,'</th>\n',
"</tr>\n",
"<tr>\n",
'\t<th style="text-align:left;border-top: 1px solid black"> Treatment </th>\n',
'\t<th style="text-align:right;border-top: 1px solid black"> Est. </th>\n',
'\t<th style="text-align:right;border-top: 1px solid black"> S.E. </th>\n',
'\t<th style="text-align:right;border-top: 1px solid black"> t-value </th>\n',
'\t<th style="text-align:right;border-top: 1px solid black"> $R^2_{Y \\sim D |{\\bf X}}$ </th>\n',
paste0('\t<th style="text-align:right;border-top: 1px solid black"> $RV_{q = ',
x$info$q, '}$ </th>\n'),
paste0('\t<th style="text-align:right;border-top: 1px solid black"> $RV_{q = ',
x$info$q, ", \\alpha = ",
x$info$alpha, "}$ </th>\n"),
"</tr>\n",
"</thead>\n"
)
# Treatment result
# Why paste and not sprintf? Easier to handle precision on the digits.
coeff_results = paste0(
"<tbody>\n <tr>\n",
'\t<td style="text-align:left; border-bottom: 1px solid black"><i>',
treatment_label, "</i></td>\n",
'\t<td style="text-align:right;border-bottom: 1px solid black">',
round(x$sensitivity_stats$estimate, digits), " </td>\n",
'\t<td style="text-align:right;border-bottom: 1px solid black">',
round(x$sensitivity_stats$se, digits), " </td>\n",
'\t<td style="text-align:right;border-bottom: 1px solid black">',
round(x$sensitivity_stats$t_statistic, digits)," </td>\n",
'\t<td style="text-align:right;border-bottom: 1px solid black">',
100 * round(x$sensitivity_stats$r2yd.x, digits), "\\% </td>\n",
'\t<td style="text-align:right;border-bottom: 1px solid black">',
100 * round(x$sensitivity_stats$rv_q, digits), "\\% </td>\n",
'\t<td style="text-align:right;border-bottom: 1px solid black">',
100 * round(x$sensitivity_stats$rv_qa, digits), "\\% </td>\n",
"</tr>\n</tbody>\n")
table_end <- "</table>"
# Foonote row: Display benchmarks
if (!is.null(x$bounds)) {
row = x$bounds[1, , drop = FALSE]
footnote = paste0('<tr>\n',
"<td colspan = 7 style='text-align:right;border-top: 1px solid black;border-bottom: 1px solid transparent;font-size:11px'>",
"Note: df = ", x$sensitivity_stats$dof, "; ",
"Bound ( ", row$bound_label, " ): ",
"$R^2_{Y\\sim Z| {\\bf X}, D}$ = ",
100 * round(row$r2yz.dx, digits),
"\\%, $R^2_{D\\sim Z| {\\bf X} }$ = ",
100 * round(row$r2dz.x, digits),
"\\%",
"</td>\n",
"</tr>\n")
} else {
footnote = paste0('<tr>\n',
"<td colspan = 7 style='text-align:right;border-top: 1px solid black;border-bottom: 1px solid transparent;font-size:11px'>",
"Note: df = ", x$sensitivity_stats$dof, "; ",
"</td>\n",
"</tr>\n")
}
# Stick it all together
table = paste0(table_begin,
coeff_header,
coeff_results,
footnote,
table_end)
# Cat to output valid LaTeX for rmarkdown
if (verbose) cat(table)
return(invisible(table))
}
html_table_no_mathjax <- function(x, digits = 3, verbose = TRUE, ...){
# Let's begin
table_settings = list(...)
outcome_label = ifelse(is.null(table_settings[["outcome_label"]]),
all.vars(x$info$formula)[1],
table_settings[["outcome_label"]])
treatment_label = ifelse(is.null(table_settings[["treatment_label"]]),
x$sensitivity_stats$treatment,
table_settings["treatment_label"])
# Okay, static beginning
table_begin = paste0("<table style='align:center'>\n")
# Coeff header row
coeff_header = paste0(
"<thead>\n",
"<tr>\n",
'\t<th style="text-align:left;border-bottom: 1px solid transparent;border-top: 1px solid black"> </th>\n',
'\t<th colspan = 6 style="text-align:center;border-bottom: 1px solid black;border-top: 1px solid black"> Outcome: ',
outcome_label,'</th>\n',
"</tr>\n",
"<tr>\n",
'\t<th style="text-align:left;border-top: 1px solid black"> Treatment </th>\n',
'\t<th style="text-align:right;border-top: 1px solid black"> Est. </th>\n',
'\t<th style="text-align:right;border-top: 1px solid black"> S.E. </th>\n',
'\t<th style="text-align:right;border-top: 1px solid black"> t-value </th>\n',
'\t<th style="text-align:right;border-top: 1px solid black"> R<sup>2</sup><sub>Y~D|X</sub> </th>\n',
paste0('\t<th style="text-align:right;border-top: 1px solid black"> RV<sub>q = ',
x$info$q, '</sub> </th>\n'),
paste0('\t<th style="text-align:right;border-top: 1px solid black"> RV<sub>q = ',
x$info$q, ", α = ",
x$info$alpha, "</sub> </th>\n"),
"</tr>\n",
"</thead>\n"
)
# Treatment result
# Why paste and not sprintf? Easier to handle precision on the digits.
coeff_results = paste0(
"<tbody>\n <tr>\n",
'\t<td style="text-align:left; border-bottom: 1px solid black"><i>',
treatment_label, "</i></td>\n",
'\t<td style="text-align:right;border-bottom: 1px solid black">',
round(x$sensitivity_stats$estimate, digits), " </td>\n",
'\t<td style="text-align:right;border-bottom: 1px solid black">',
round(x$sensitivity_stats$se, digits), " </td>\n",
'\t<td style="text-align:right;border-bottom: 1px solid black">',
round(x$sensitivity_stats$t_statistic, digits)," </td>\n",
'\t<td style="text-align:right;border-bottom: 1px solid black">',
100 * round(x$sensitivity_stats$r2yd.x, digits), "\\% </td>\n",
'\t<td style="text-align:right;border-bottom: 1px solid black">',
100 * round(x$sensitivity_stats$rv_q, digits), "\\% </td>\n",
'\t<td style="text-align:right;border-bottom: 1px solid black">',
100 * round(x$sensitivity_stats$rv_qa, digits), "\\% </td>\n",
"</tr>\n</tbody>\n")
table_end <- "</table>"
# Foonote row: Display benchmarks
if (!is.null(x$bounds)) {
row = x$bounds[1, , drop = FALSE]
footnote = paste0('<tr>\n',
"<td colspan = 7 style='text-align:right;border-bottom: 1px solid transparent;font-size:11px'>",
"Note: df = ", x$sensitivity_stats$dof, "; ",
"Bound ( ", row$bound_label, " ): ",
"R<sup>2</sup><sub>Y~Z|X,D</sub> = ",
100 * round(row$r2yz.dx, digits),
"\\%, R<sup>2</sup><sub>D~Z|X</sub> = ",
100 * round(row$r2dz.x, digits),
"\\%",
"</td>\n",
"</tr>\n")
} else {
footnote = paste0('<tr>\n',
"<td colspan = 7 style='text-align:right;border-bottom: 1px solid transparent;font-size:11px'>",
"Note: df = ", x$sensitivity_stats$dof, "; ",
"</td>\n",
"</tr>\n")
}
# Stick it all together
table = paste0(table_begin,
coeff_header,
coeff_results,
footnote,
table_end)
# Cat to output valid LaTeX for rmarkdown
if (verbose) cat(table)
return(invisible(table))
}