### Install and Manage Causal Inference Task View Source: https://context7.com/cran-task-views/causalinference/llms.txt Installs, updates, or reads the metadata for the CausalInference task view using the ctv package. Ensure the ctv package is installed first. ```r # Install the ctv package install.packages("ctv") ``` ```r # Install all packages in the CausalInference task view ctv::install.views("CausalInference") ``` ```r # Update already-installed task view packages ctv::update.views("CausalInference") ``` ```r # Read the task view metadata locally (for contributors) ctv::read.ctv("CausalInference.md") #> $name #> [1] "CausalInference" #> $packagelist #> package priority #> 1 MatchIt core #> 2 WeightIt core #> ... ``` -------------------------------- ### Get Synthetic Control Significance Source: https://context7.com/cran-task-views/causalinference/llms.txt Retrieves and displays significance test results for the synthetic control analysis, including p-values and z-scores. ```R library(tidysynth) synth_out |> grab_significance() #> unit_name type fishers_exact_pvalue z_score #> California Treated 0.0370 -2.41 ``` -------------------------------- ### Create and Plot a Policy Tree Source: https://context7.com/cran-task-views/causalinference/llms.txt Uses the policytree package to create a policy tree from data and then plots the resulting tree. ```R library(policytree) pt <- policy_tree(X, cf, depth = 2) plot(pt) ``` -------------------------------- ### Export Causal Packages to File Source: https://context7.com/cran-task-views/causalinference/llms.txt Exports a unique list of causal package names to a text file for manual review. Displays the count of candidate packages found. ```R write.table(unique(causal_pkgs$Package), file = "data/causal_packages.txt", row.names = FALSE, col.names = FALSE, quote = FALSE) message(n_distinct(causal_pkgs$Package), " candidate packages found") ``` -------------------------------- ### Build Synthetic Control with tidysynth Source: https://context7.com/cran-task-views/causalinference/llms.txt Constructs a synthetic control group using the tidysynth package. This involves generating predictors and weights based on specified time windows and optimization. ```R library(tidysynth) data("smoking", package = "tidysynth") # California Prop 99 tobacco data synth_out <- smoking |> synthetic_control(outcome = cigsale, unit = unit, time = year, i_unit = "California", i_time = 1988, generate_placebos = TRUE) |> generate_predictor(time_window = 1980:1988, ln_income = mean(lnincome), retail_price = mean(retprice), beer_sales = mean(beer)) |> generate_predictor(time_window = 1984:1988, cigsale_84_88 = mean(cigsale)) |> generate_weights(optimization_window = 1970:1988) |> generate_control() ``` -------------------------------- ### Learn Causal Structure with PC Algorithm Source: https://context7.com/cran-task-views/causalinference/llms.txt Applies the PC algorithm from the pcalg package to learn a causal structure from observational data. Requires a suffStat object containing correlation matrix and sample size. ```R library(pcalg) library(dagitty) library(ggdag) # 1. PC algorithm for causal structure learning from observational data data("gmG8", package = "pcalg") # Gaussian data, 8 variables suffStat <- list(C = cor(gmG8$x), n = nrow(gmG8$x)) pc_fit <- pc(suffStat, indepTest = gaussCItest, alpha = 0.05, labels = colnames(gmG8$x), verbose = FALSE) plot(pc_fit, main = "PC Algorithm CPDAG") ``` -------------------------------- ### Estimate ATE using Entropy Balancing Weights Source: https://context7.com/cran-task-views/causalinference/llms.txt Estimates ATE using entropy balancing weights with the WeightIt package and fits a weighted linear model. Requires the WeightIt package. ```r # 2. Entropy balancing weights w_out <- weightit(treat ~ age + educ + race + re74 + re75, data = lalonde, method = "ebal", estimand = "ATE") fit_w <- lm(re78 ~ treat, data = lalonde, weights = w_out$weights) summary(fit_w) ``` -------------------------------- ### Estimate Average Treatment Effect (ATE) using Matching Source: https://context7.com/cran-task-views/causalinference/llms.txt Performs propensity score matching using the MatchIt package and estimates the ATE by fitting a linear model on the matched data. Requires the MatchIt and marginaleffects packages. ```r library(MatchIt) library(WeightIt) library(marginaleffects) data("lalonde", package = "MatchIt") # 1. Propensity score matching m_out <- matchit(treat ~ age + educ + race + re74 + re75, data = lalonde, method = "nearest", ratio = 1) m_data <- match.data(m_out) fit_m <- lm(re78 ~ treat + age + educ + race + re74 + re75, data = m_data, weights = weights) avg_comparisons(fit_m, variables = "treat") #> Estimate Std. Error z Pr(>|z|) S 2.5 % 97.5 % #> 1205 578 2.08 0.0372 4.75 71 2338 ``` -------------------------------- ### Discover Causal Inference CRAN Packages Source: https://context7.com/cran-task-views/causalinference/llms.txt Automates the discovery of relevant CRAN packages for causal inference by text-mining package descriptions and comparing them against a list of keywords and existing task view packages. ```R library(tidytext) library(tidyverse) # Keywords signalling causal-inference relevance mda_words <- c("causal", "causal inference", "treatment effect", "ATE", "HTE", "propensity score", "potential outcomes", "RCT", "instrumental variable", "IPW", "do-calculus") # Read currently listed packages from the task view source listed_packages <- ctv::read.ctv("CausalInference.md")$packagelist[, 1] # Download full CRAN package database cran_db <- tools::CRAN_package_db() cran_tbl <- tibble::as_tibble(cran_db[, -65]) |> select(Package, Description) # Tokenise descriptions and filter by keywords data("stop_words") causal_pkgs <- cran_tbl |> unnest_tokens(word, Description) |> anti_join(stop_words, by = "word") |> group_by(Package) |> filter(tolower(word) %in% mda_words) |> ungroup() # New candidates not yet in the task view new_candidates <- causal_pkgs |> filter(!Package %in% listed_packages) |> distinct(Package) ``` -------------------------------- ### Doubly Robust Estimation with TMLE and AIPW Source: https://context7.com/cran-task-views/causalinference/llms.txt Demonstrates TMLE and AIPW for doubly robust estimation. Requires outcome and propensity model specification. TMLE uses Super Learner for flexible modeling. ```r library(tmle) set.seed(1) n <- 500 W <- data.frame(W1 = rnorm(n), W2 = rbinom(n, 1, 0.4)) A <- rbinom(n, 1, plogis(0.3 * W$W1 - 0.2 * W$W2)) Y <- rnorm(n, mean = 2 * A + W$W1 - W$W2, sd = 1) # TMLE with Super Learner result <- tmle(Y = Y, A = A, W = W, family = "gaussian", g.SL.library = c("SL.glm", "SL.ranger"), Q.SL.library = c("SL.glm", "SL.ranger")) summary(result) #> Additive Effect #> Parameter Estimate: 1.98 #> Estimated Variance: 0.0042 #> #> p-value: <2e-16 #> #> 95% Conf Interval: (1.85, 2.11) ``` ```r library(AIPW) aipw <- AIPW$new(Y = Y, A = A, W = W, Q.SL.library = c("SL.glm","SL.ranger"), g.SL.library = c("SL.glm","SL.ranger"), k_split = 3) aipw$fit()$summary() ``` -------------------------------- ### Identify Adjustment Set using DAGitty Source: https://context7.com/cran-task-views/causalinference/llms.txt Uses the dagitty package to define a Directed Acyclic Graph (DAG) and identify necessary adjustment sets for estimating causal effects. ```R library(pcalg) library(dagitty) library(ggdag) # 2. Identify adjustment set using DAGitty dag <- dagitty("dag { X -> M -> Y X -> Y U -> M U -> Y }") adjustmentSets(dag, exposure = "X", outcome = "Y") #> { } (no adjustment needed for total effect X->Y, but M is a collider) ``` -------------------------------- ### Analyze Randomized Controlled Trials (RCTs) Source: https://context7.com/cran-task-views/causalinference/llms.txt Provides tools for simulating RCT data and performing intent-to-treat analysis using linear models. Also includes power analysis for multi-level RCTs. ```r library(experiment) # Simulate a simple two-arm RCT set.seed(42) n <- 200 data_rct <- data.frame( Y = rnorm(n, mean = 5, sd = 2), Z = rbinom(n, 1, 0.5), # treatment assignment X1 = rnorm(n), # covariate X2 = rbinom(n, 1, 0.4) ) # Intent-to-treat analysis itt <- lm(Y ~ Z + X1 + X2, data = data_rct) summary(itt) #> Coefficients: #> Estimate Std. Error t value Pr(>|t|) #> (Intercept) 4.9821 0.2213 22.51 <2e-16 *** #> Z 0.1234 0.2819 0.44 0.662 ``` ```r # Power analysis for multi-level RCT library(cosa) cosa.Bird2016( es = 0.25, # target effect size n = c(20, 10), # students per classroom, classrooms per school p = 0.5 # proportion treated ) ``` -------------------------------- ### Estimate ATE using Double Machine Learning Source: https://context7.com/cran-task-views/causalinference/llms.txt Applies Double/debiased Machine Learning (DML) for ATE estimation using the DoubleML package with ranger learners. Requires DoubleML, mlr3, and mlr3learners packages. ```r # 3. Double/debiased machine learning library(DoubleML) library(mlr3) library(mlr3learners) dml_data <- DoubleMLData$new(lalonde, y_col = "re78", d_cols = "treat", x_cols = c("age","educ","re74","re75")) lrn_rf <- lrn("regr.ranger", num.trees = 200) dml_plr <- DoubleMLPLR$new(dml_data, ml_l = lrn_rf, ml_m = lrn_rf) dml_plr$fit() dml_plr$summary() #> Estimates and significance testing of the effect of target variables #> Estimate. Std. Error t value Pr(>|t|) #> treat 1423.0 517.3 2.751 0.00594 ** ``` -------------------------------- ### Visualize DAG and Adjustment Set with ggdag Source: https://context7.com/cran-task-views/causalinference/llms.txt Visualizes a DAG and its identified adjustment set using ggplot2 via the ggdag package. ```R library(pcalg) library(dagitty) library(ggdag) # 3. Visualise DAG in ggplot2 ggdag_adjustment_set( tidy_dagitty(dag), exposure = "X", outcome = "Y" ) + theme_dag() ``` -------------------------------- ### Regression Discontinuity Design (RDD) Source: https://context7.com/cran-task-views/causalinference/llms.txt Applies RDD estimation with optimal bandwidth selection and robust bias-corrected confidence intervals. Includes density tests for manipulation. ```r library(rdrobust) data("rdrobust_RDsenate", package = "rdrobust") # x = margin of victory, y = vote share in next election rdd <- rdrobust(y = rdrobust_RDsenate$vote, x = rdrobust_RDsenate$margin, kernel = "triangular", bwselect = "mserd") summary(rdd) #> RD Estimates: #> Coef. Std. Err. z P>|z| [ 95% C.I. ] #> Conventional 6.97 1.43 4.87 <0.001 [ 4.16, 9.77] #> Bias-Corrected 7.00 1.43 4.89 <0.001 [ 4.19, 9.81] #> Robust 7.00 1.74 4.02 <0.001 [ 3.59, 10.41] ``` ```r rddensity::rddensity(rdrobust_RDsenate$margin) |> summary() ``` ```r rdplot(y = rdrobust_RDsenate$vote, x = rdrobust_RDsenate$margin, title = "Senate Incumbency Advantage") ``` -------------------------------- ### Causal Forests for Heterogeneous Treatment Effects Source: https://context7.com/cran-task-views/causalinference/llms.txt Estimates heterogeneous treatment effects using causal forests. Requires specifying covariates (X), outcomes (Y), and treatment assignment (W). Supports ATE, CATE, and heterogeneity testing. ```r library(grf) data("lalonde", package = "MatchIt") X <- model.matrix(~ age + educ + re74 + re75 - 1, data = lalonde) Y <- lalonde$re78 W <- lalonde$treat # Causal forest cf <- causal_forest(X = X, Y = Y, W = W, num.trees = 2000, tune.parameters = "all") # Average treatment effect average_treatment_effect(cf, target.sample = "all") #> estimate std.err #> 1462.41 540.63 # Conditional average treatment effects (CATEs) cates <- predict(cf)$predictions # Best linear projection onto covariates best_linear_projection(cf, A = X) # Test for heterogeneity test_calibration(cf) #> Estimate Std. Error t value Pr(>|t|) #> mean.forest.prediction 1.0022 0.4519 2.218 0.02716 * #> differential.forest.pred 0.9718 0.6105 1.592 0.11188 ``` -------------------------------- ### Plot Synthetic Control Placebos Source: https://context7.com/cran-task-views/causalinference/llms.txt Generates and plots placebo tests for the synthetic control analysis, which involves running the synthetic control method on different units or time periods. ```R library(tidysynth) synth_out |> plot_placebos() # permutation-based inference ``` -------------------------------- ### Perform Causal Mediation Analysis Source: https://context7.com/cran-task-views/causalinference/llms.txt Conducts causal mediation analysis using the mediation package, estimating Average Causal Mediation Effects (ACME) and Average Direct Effects (ADE). Requires fitting mediator and outcome models first. ```R library(mediation) data("jobs", package = "mediation") # Fit mediator and outcome models model.m <- lm(job_seek ~ treat + depress1 + econ_hard + sex + age, data = jobs) model.y <- lm(depress2 ~ treat + job_seek + depress1 + econ_hard + sex + age, data = jobs) # Causal mediation analysis (ACME + ADE) set.seed(2014) med_out <- mediate(model.m, model.y, treat = "treat", mediator = "job_seek", boot = TRUE, sims = 1000) summary(med_out) #> Estimate 95% CI Lower 95% CI Upper p-value #> ACME (control) -0.0142 -0.0307 0.00 0.08 #> ACME (treated) -0.0142 -0.0307 0.00 0.08 #> ADE (control) -0.0439 -0.1208 0.03 0.26 #> Total Effect -0.0581 -0.1371 0.02 0.17 #> Prop. Mediated 0.2443 -0.5843 1.57 0.17 ``` -------------------------------- ### Plot Synthetic Control Differences Source: https://context7.com/cran-task-views/causalinference/llms.txt Visualizes the difference between the outcome of the treated unit and its synthetic control over time. ```R library(tidysynth) synth_out |> plot_differences() ``` -------------------------------- ### Difference-in-Differences with Staggered Adoption Source: https://context7.com/cran-task-views/causalinference/llms.txt Implements Callaway & Sant'Anna (2021) and Sun & Abraham estimators for DiD with staggered treatment adoption. Requires specifying outcome, treatment timing, and covariates. ```r library(did) # Callaway & Sant'Anna (2021) estimator with staggered treatment data("mpdta", package = "did") # mpdta: county-level minimum wage data, first.treat = year of treatment out <- att_gt(yname = "lemp", gname = "first.treat", idname = "countyreal", tname = "year", xformla = ~lpop, data = mpdta, est_method = "dr") # doubly robust # Aggregate to simple ATT simple_att <- aggte(out, type = "simple") summary(simple_att) #> ATT SE [ 95% Conf. Int.] #> -0.0323 0.0124 -0.0565 -0.0080 # Event-study plot ggdid(aggte(out, type = "dynamic"), ylim = c(-0.15, 0.10)) ``` ```r library(fixest) feols(lemp ~ sunab(first.treat, year) + lpop | countyreal + year, data = mpdta) |> iplot() ``` -------------------------------- ### Sensitivity Analysis for Unmeasured Confounding Source: https://context7.com/cran-task-views/causalinference/llms.txt Performs a sensitivity analysis for unmeasured confounding in mediation analysis using the medsens function from the mediation package. ```R library(mediation) sens_out <- medsens(med_out, rho.by = 0.05, effect.type = "indirect") plot(sens_out, main = "Sensitivity: ACME") ``` -------------------------------- ### Instrumental Variables Regression Source: https://context7.com/cran-task-views/causalinference/llms.txt Performs 2SLS and LIML estimation for instrumental variables. The first formula specifies endogenous and exogenous covariates, while the second specifies instruments. ```r library(ivreg) # Classic Card (1995) returns-to-education IV data("CigarettesSW", package = "AER") # Two-stage least squares: proximity to college as instrument for education iv_fit <- ivreg(log(packs) ~ log(price) + log(income) | log(rincome) + tdiff, data = CigarettesSW) summary(iv_fit, diagnostics = TRUE) #> Diagnostic tests: #> #> df1 df2 statistic p-value #> Weak instruments 1 44 244.73 <2e-16 *** #> Wu-Hausman 1 43 5.12 0.0286 * #> Sargan 0 NA NA NA ``` ```r library(fixest) feiv(re78 ~ 1 | age + educ | treat ~ nearc4, data = MatchIt::lalonde) ``` -------------------------------- ### Plot Synthetic Control Trends Source: https://context7.com/cran-task-views/causalinference/llms.txt Plots the trends of the outcome variable for the treated unit and its synthetic control. ```R library(tidysynth) synth_out |> plot_trends() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.