--- title: "From a fitted model to a sensitivity report" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{From a fitted model to a sensitivity report} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} has_sm <- requireNamespace("sensemakr", quietly = TRUE) has_kf <- requireNamespace("konfound", quietly = TRUE) has_ev <- requireNamespace("EValue", quietly = TRUE) has_dos2 <- requireNamespace("DOS2", quietly = TRUE) has_iv <- requireNamespace("iv.sensemakr", quietly = TRUE) has_dml <- requireNamespace("DoubleML", quietly = TRUE) && requireNamespace("mlr3learners", quietly = TRUE) knitr::opts_chunk$set(collapse = TRUE, comment = "#>", fig.width = 6.5, fig.height = 4, eval = has_sm) ``` ```{r, eval = !has_sm, echo = FALSE, results = "asis"} cat("*This vignette needs the 'sensemakr' package for the example data;", "install it to see the output.*") ``` This vignette walks through the complete workflow: ``` fitted model -> sensitivity path -> confoundsens object -> plots -> report ``` The datasets below illustrate the workflow. For your own analysis, pass a fitted model or other supported input from your study. ## Data and model The `darfur` data (Hazlett, 2020), distributed with the **sensemakr** package, come from a survey of Darfurian refugees in eastern Chad. The question is whether being directly harmed in the violence (`directlyharmed`) changed attitudes toward peace (`peacefactor`). Following Cinelli and Hazlett (2020), we adjust for age, occupation, past voting, household size, sex, and village fixed effects. ```{r model} library(confoundvis) data("darfur", package = "sensemakr") fit <- lm(peacefactor ~ directlyharmed + age + farmer_dar + herder_dar + pastvoted + hhsize_darfur + female + village, data = darfur) coef(summary(fit))["directlyharmed", ] ``` ## Step 1: compute sensitivity paths A *sensitivity path* is the treatment estimate as a function of the strength $\lambda$ of a hypothetical omitted confounder. `confoundvis` computes paths for two regression frameworks directly from the fitted model. **Partial $R^2$ (Cinelli and Hazlett, 2020).** $\lambda$ is the partial $R^2$ of the confounder with both treatment and outcome: ```{r path-r2} p_r2 <- sens_path_lm(fit, treatment = "directlyharmed", lambda = seq(0, 0.3, by = 0.001)) p_r2 ``` **Impact threshold (Frank, 2000).** $\lambda$ is the impact $k = r_{DU}\,r_{YU}$; the path is the adjusted partial correlation: ```{r path-itcv} it <- itcv_lm(fit, treatment = "directlyharmed", lambda = seq(0, 0.3, by = 0.001)) c(r = it$r, r_crit = it$r_crit, ITCV = it$itcv, ITCV_unconditional = it$itcv_unconditional) ``` Both results are `confoundsens` objects, so everything downstream is the same regardless of framework. ## Step 2: plot the paths ```{r curve-r2} plot_robustness_curve(p_r2, points = FALSE) ``` The dotted line is the null. The band is a pointwise 95% interval for the bias-adjusted estimate. ```{r curve-itcv} plot_robustness_curve(it$path, points = FALSE) ``` On the ITCV path the dashed line marks the critical correlation; the path crosses it exactly at the ITCV. ## Step 3: benchmark against observed covariates A threshold alone does not say whether an omitted confounder that strong is plausible. The usual aid is to compare it with observed covariates. `covariate_impacts()` computes, for every covariate term, its partial associations with treatment and outcome. ```{r impacts} imp <- covariate_impacts(fit, "directlyharmed", metric = "partial_r2") imp[order(-imp$impact), c("covariate", "term_df", "r2dz.x", "r2yz.dx", "bias_index")] ``` The sensitivity Love plot places each covariate on the chosen metric and draws the threshold. With `metric = "partial_r2"`, a covariate to the right of the line would, if an omitted confounder were equally strong, bring the point estimate to zero. ```{r love} plot_sensitivity_love(imp) ``` The ITCV metric uses signed products of partial correlations and is defined for single-column terms; the multi-column `village` term is dropped with a message. ```{r love-itcv} imp_it <- covariate_impacts(fit, "directlyharmed", metric = "itcv") plot_sensitivity_love(imp_it) ``` The same object supplies benchmarks for the contour plot. Passing the `itcv_lm()` result draws the exact significance boundary (solid) next to the product reference $|r_{YU} r_{DU}| = \text{ITCV}$ (dashed). The two agree only for confounders whose two correlations have equal magnitude; elsewhere the exact boundary decides. Pairs that no correlation matrix can produce are shaded as infeasible. ```{r contour, fig.width = 6, fig.height = 6.3} plot_sensitivity_contour(itcv = it, benchmarks = imp_it[!is.na(imp_it$r_yu), ], limits = c(-0.5, 0.5)) ``` ## Step 4: a plain-language report ```{r report} sens_report(p_r2) sens_report(it$path) ``` `robustness_points()` returns the same numbers as a data frame for tables. On the partial $R^2$ path, the null crossing is the robustness value and the significance crossing is the robustness value at $\alpha = 0.05$ reported by **sensemakr**. ## Using results from other packages If an analysis was run with another package, convert its result instead of recomputing it. ```{r sensemakr} s <- sensemakr::sensemakr(fit, treatment = "directlyharmed", benchmark_covariates = "female", kd = 1:3) p_sm <- from_sensemakr(s, lambda = seq(0, 0.3, by = 0.001)) robustness_points(p_sm) unlist(s$sensitivity_stats[c("rv_q", "rv_qa")]) ``` ```{r konfound, eval = has_sm && has_kf} k <- suppressWarnings(suppressMessages( konfound::konfound(fit, directlyharmed, to_return = "raw_output"))) p_kf <- from_konfound(k, lambda = seq(0, 0.3, by = 0.001)) c(confoundvis = it$itcv, konfound_itcvGz = k$itcvGz) ``` For binary or ratio-scale outcomes, E-value results convert to a path on the log risk-ratio scale that crosses the null at the E-value: ```{r evalue, eval = has_ev} e <- EValue::evalues.RR(est = 1.8, lo = 1.3, hi = 2.5) p_ev <- from_evalue(e, lambda = seq(1, 4, by = 0.01)) plot_robustness_curve(p_ev, points = FALSE) ``` ## Matched designs: Rosenbaum bounds For a matched-pair study, `sens_path_pairs()` computes the path under Rosenbaum's sensitivity model, in which two matched units may differ in their odds of treatment by at most a factor $\Gamma$. The path stores, for each $\Gamma$, the deviate equivalent to the upper bound on the one-sided P-value, so the same crossing, plotting, and reporting functions apply. The `werfel` data in **DOS2** compare DNA damage in 39 welders and 39 controls matched for age and smoking. ```{r pairs, eval = has_dos2} data("werfel", package = "DOS2") d <- werfel$serpc_p - werfel$cerpc_p p_gam <- sens_path_pairs(d, gamma = seq(1, 6, by = 0.01)) robustness_points(p_gam) sens_report(p_gam) plot_robustness_curve(p_gam, points = FALSE) ``` The result agrees with `DOS2::senWilcox()`. For a binary outcome, use `method = "binary"`, which applies the exact bound for McNemar's statistic. ## Binary outcomes: risk differences and a practical threshold For a binary outcome analysed with logistic regression, a decision often rests on the absolute size of an effect, not only on its sign. `sens_risk_difference()` describes a hypothetical binary confounder by its prevalence among the treated (`p1`) and untreated (`p0`) and its odds ratio with the outcome (Lin, Psaty, and Kronmal, 1998). For each odds ratio it returns the risk difference standardized to the study population, with a standard error, and it reports the odds ratios at which the risk difference reaches a practical threshold and zero. This example simulates a binary outcome, a binary treatment, and a measured baseline covariate. To apply the same workflow to your study, fit an unweighted binomial model with the `data` argument and pass the name of your binary treatment variable. Choose `p1`, `p0`, and the risk-difference threshold for your own analysis. The values below illustrate the function. ```{r rd, eval = TRUE} library(confoundvis) set.seed(104) n <- 2000 example_data <- data.frame(baseline = rnorm(n)) example_data$treated <- rbinom(n, 1, plogis(-0.2 + 0.5 * example_data$baseline)) example_data$event <- rbinom( n, 1, plogis(-1.5 + 0.45 * example_data$treated + 0.4 * example_data$baseline) ) fit_b <- glm(event ~ treated + baseline, family = binomial(), data = example_data) rd <- sens_risk_difference(fit_b, "treated", p1 = 0.4, p0 = 0.2, threshold = 0.02) sens_report(rd) plot_robustness_curve(rd, points = FALSE) ``` The dot-dash line is the practical threshold of 2 extra events per 100 people. The path shows how the conclusion changes across confounding scenarios; the band shows sampling error within each scenario. These are different sources of uncertainty, and the report keeps them apart. With no confounding, the estimate equals `marginaleffects::avg_comparisons()` for the treatment. `confounder_effect = "risk_difference"` gives the additive version, which equals the correction of `episensr::confounders(type = "RD")`; scenarios that would imply risks outside $[0, 1]$ are not used. ## Instrumental variables and double machine learning `from_iv_sensemakr()` imports the sensitivity analysis of an instrumental variable estimate from **iv.sensemakr** (Cinelli and Hazlett, 2025) and reproduces its robustness values and benchmark bounds. ```{r iv, eval = has_iv} data("card", package = "iv.sensemakr") xm <- model.matrix(~ exper + expersq + black + south + smsa + reg661 + reg662 + reg663 + reg664 + reg665 + reg666 + reg667 + reg668 + smsa66, data = card) iv <- iv.sensemakr::iv_fit(card$lwage, card$educ, card$nearc4, xm) p_iv <- from_iv_sensemakr(iv.sensemakr::sensemakr(iv, benchmark_covariates = c("black", "smsa"))) robustness_points(p_iv) ``` `sens_dml()` computes the omitted-variable-bias bounds of Chernozhukov et al. (2024) for a fit from the R package **DoubleML**, which does not provide them, following the Python package **doubleml**. ```{r dml, eval = has_dml} library(DoubleML) set.seed(1) dat <- make_plr_CCDDHNR2018(n_obs = 500, return_type = "data.table") plr <- DoubleMLPLR$new(DoubleMLData$new(dat, y_col = "y", d_cols = "d"), ml_l = mlr3::lrn("regr.lm"), ml_m = mlr3::lrn("regr.lm")) plr$fit(store_predictions = TRUE) p_dml <- sens_dml(plr) robustness_points(p_dml) ``` ## Two-parameter surfaces Each framework describes an omitted confounder with two parameters, one for its association with treatment and one for its association with the outcome. A path is one line through that plane. `sens_surface()` returns the whole plane with the boundaries at which the conclusion changes, computed from the framework's published formula. The partial $R^2$ surface is the plane of `sensemakr::ovb_contour_plot()`; benchmarks from `covariate_impacts()` are placed on it automatically. ```{r surface-r2, fig.width = 6.5, fig.height = 5} s_r2 <- sens_surface(p_r2) s_r2 plot_sensitivity_surface(s_r2, benchmarks = head(imp[order(-imp$impact), ], 4)) ``` For a matched-pair study, the surface shows the amplification of $\Gamma$ (Rosenbaum and Silber, 2009): every pair $(\Lambda, \Delta)$ on the solid curve corresponds to the sensitivity value, as in `sensitivitymv::amplify()`. ```{r surface-pairs, eval = has_dos2, fig.width = 6.5, fig.height = 5} plot_sensitivity_surface(sens_surface(p_gam)) ``` The size of a shaded zone depends on the axis ranges and carries no inferential meaning; the surface is read only through its boundaries. ## Several analyses in one table `sens_table()` collects the decision information of several paths, each in its own units. It is intended for reporting several analyses side by side, not for ranking them: a robustness value, an impact threshold, and a value of $\Gamma$ measure different things. ```{r table} sens_table(partial_r2 = p_r2, itcv = it$path, sensemakr = p_sm) ``` ## What this package does and does not do `confoundvis` is a presentation layer. Its computations reproduce the published formulas of each framework (the test suite checks them against **sensemakr**, **konfound**, and **EValue**), and its contribution is a shared object and a shared set of displays. It inherits every assumption of the framework that generated a path. In particular: * A sensitivity path answers "how strong would confounding have to be?", not "is there such a confounder?" Only substantive knowledge can judge that. * Covariate benchmarks describe observed variables. An omitted confounder can be stronger than every measured covariate, and benchmarks can themselves be distorted when the omitted confounder is correlated with them. * The partial $R^2$ and ITCV paths are for linear regression coefficients. The E-value path concerns ratio measures; its bias factor is a bound, not an exact adjustment. * No display repairs a flawed identification strategy (for example, bad controls, selection, or measurement error in the treatment). * confoundvis adds no new sensitivity parameter or measure. Every number it reports is the published quantity of the framework that produced it. ## References Rosenbaum, P. R., & Silber, J. H. (2009). Amplification of sensitivity analysis in matched observational studies. *Journal of the American Statistical Association*, 104(488), 1398–1405. Cinelli, C., & Hazlett, C. (2020). Making sense of sensitivity: Extending omitted variable bias. *Journal of the Royal Statistical Society: Series B*, 82(1), 39–67. Frank, K. A. (2000). Impact of a confounding variable on a regression coefficient. *Sociological Methods & Research*, 29(2), 147–194. Frank, K. A., Maroulis, S. J., Duong, M. Q., & Kelcey, B. M. (2013). What would it take to change an inference? *Educational Evaluation and Policy Analysis*, 35(4), 437–460. Hazlett, C. (2020). Angry or weary? How violence impacts attitudes toward peace among Darfurian refugees. *Journal of Conflict Resolution*, 64(5), 844–870. Rosenbaum, P. R. (2002). *Observational Studies* (2nd ed.). Springer. VanderWeele, T. J., & Ding, P. (2017). Sensitivity analysis in observational research: Introducing the E-value. *Annals of Internal Medicine*, 167(4), 268–274. Chernozhukov, V., Cinelli, C., Newey, W., Sharma, A., & Syrgkanis, V. (2024). Long story short: Omitted variable bias in causal machine learning. NBER Working Paper 30302. Cinelli, C., & Hazlett, C. (2025). An omitted variable bias framework for sensitivity analysis of instrumental variables. *Biometrika*, 112(2), asaf004. Lin, D. Y., Psaty, B. M., & Kronmal, R. A. (1998). Assessing the sensitivity of regression results to unmeasured confounders in observational studies. *Biometrics*, 54(3), 948–963.