View source: R/synthetic-control.R
| run_synth_bsts | R Documentation |
Builds a simple synthetic-control-style analysis using
CausalImpact/BSTS for either I or C as the outcome,
with treatment defined endogenously by a high level of a chosen
control variable.
run_synth_bsts(
DT,
outcome = c("I", "C"),
control_var,
seed = 123,
dir_csv = NULL
)
DT |
A
|
outcome |
Character; which outcome series to use as the response,
one of |
control_var |
Character scalar; name of a column in |
seed |
Integer; random seed for reproducibility of the BSTS fit. |
dir_csv |
Character scalar or |
This function requires the CausalImpact package (listed under
Suggests); an informative error is raised at call time if it is
not installed.
The function:
Selects the outcome series y <- DT[[outcome]].
Builds the predictor matrix from
EconCycle, PopDensity, Epidemics,
Climate, War, and t_norm.
Uses control_var to define a treated period as
observations where control_var is in the top third
(>= 2/3 quantile). If fewer than 5 treated observations
are found, the function returns NULL.
Sets the intervention start time t0 as one period before
the first treated index (with a minimum of 10 observations in
the pre-period). The pre- and post-intervention windows are:
pre.period = c(1, t0) and
post.period = c(t0 + 1, length(y)).
Calls CausalImpact::CausalImpact() on the combined
cbind(y, preds) matrix, with model.args = list(nseasons = 1).
From the resulting impact object, the function extracts the
average absolute and relative effects from impact$summary and
stores them in a small summary table with two rows:
"abs_effect_mean" and "rel_effect_mean".
When dir_csv is supplied, a CSV file named
"causalimpact_<control_var>_on_<outcome>.csv" is written to that
directory. If CausalImpact() fails, the function returns
NULL.
On success, a list with components:
impact: the full CausalImpact object.
summary: a data.frame with the mean absolute and
relative effects.
If the treated period is too short or the model fit fails, the function
returns NULL.
# This example runs only when 'CausalImpact' is installed.
if (requireNamespace("CausalImpact", quietly = TRUE)) {
DT <- data.frame(
I = rpois(30, lambda = 10),
C = rpois(30, lambda = 8),
EconCycle = rnorm(30),
PopDensity = rnorm(30),
Epidemics = rnorm(30),
Climate = rnorm(30),
War = rnorm(30),
t_norm = seq(-1, 1, length.out = 30)
)
res_I <- run_synth_bsts(DT, outcome = "I", control_var = "War", seed = 123)
if (!is.null(res_I)) {
print(res_I$summary)
}
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.