# Setup for examples
design <-
declare_model(
N = 500,
gender = rbinom(N, 1, 0.5),
U = rnorm(N, sd = 0.25),
potential_outcomes(Y ~ rbinom(
N, 1, prob = pnorm(0.2 * Z + 0.2 * gender + 0.1 * Z * gender + U)
))
) +
declare_inquiry(ATE = mean(Y_Z_1 - Y_Z_0)) +
declare_sampling(S = complete_rs(N = N, n = 200)) +
declare_assignment(Z = complete_ra(N = N, m = 100)) +
declare_measurement(Y = reveal_outcomes(Y ~ Z))
run_design(design)
# default estimator is lm_robust with tidy summary
design_0 <-
design +
declare_estimator(Y ~ Z, inquiry = "ATE")
run_design(design_0)
# Linear regression using lm_robust and tidy summary
design_1 <-
design +
declare_estimator(
formula = Y ~ Z,
.method = lm_robust,
.summary = tidy,
term = "Z",
inquiry = "ATE",
label = "lm_no_controls"
)
run_design(design_1)
# Use glance summary function to view model fit statistics
design_2 <-
design +
declare_estimator(.method = lm_robust,
formula = Y ~ Z,
.summary = glance)
run_design(design_2)
# Use declare_estimator to implement custom answer strategies
my_estimator <- function(data) {
data.frame(estimate = mean(data$Y))
}
design_3 <-
design +
declare_inquiry(Y_bar = mean(Y)) +
declare_estimator(handler = label_estimator(my_estimator),
label = "mean",
inquiry = "Y_bar")
run_design(design_3)
# Use `term` to select particular coefficients
design_4 <-
design +
declare_inquiry(difference_in_cates = mean(Y_Z_1[gender == 1] - Y_Z_0[gender == 1]) -
mean(Y_Z_1[gender == 0] - Y_Z_0[gender == 0])) +
declare_estimator(Y ~ Z * gender,
term = "Z:gender",
inquiry = "difference_in_cates",
.method = lm_robust)
run_design(design_4)
# Use glm from base R
design_5 <-
design +
declare_estimator(Y ~ Z + gender,
family = "gaussian",
inquiry = "ATE",
.method = glm)
run_design(design_5)
# If we use logit, we'll need to estimate the average marginal effect with
# margins::margins. We wrap this up in function we'll pass to model_summary
library(margins) # for margins
library(broom) # for tidy
tidy_margins <- function(x) {
tidy(margins(x, data = x$data), conf.int = TRUE)
}
design_6 <-
design +
declare_estimator(
Y ~ Z + gender,
.method = glm,
family = binomial("logit"),
.summary = tidy_margins,
term = "Z"
)
run_design(design_6)
# Multiple estimators for one inquiry
design_7 <-
design +
declare_estimator(Y ~ Z,
.method = lm_robust,
inquiry = "ATE",
label = "OLS") +
declare_estimator(
Y ~ Z + gender,
.method = glm,
family = binomial("logit"),
.summary = tidy_margins,
inquiry = "ATE",
term = "Z",
label = "logit"
)
run_design(design_7)
Run the code above in your browser using DataCamp Workspace