# tidysynth
## Overview
`tidysynth` is a tidy implementation the [synthetic control method](https://en.wikipedia.org/wiki/Synthetic_control_method) in `R`. A synthetic control offers a way of evaluating the effect of an intervention in comparative case studies. The method aims to model a counterfactual unit using a weighted average of units that did not receive the intervention. The effect of the intervention can be estimated by comparing differences in the observed and synthetic time series. See Abadie et al. [2003](https://www.aeaweb.org/articles?id=10.1257/000282803321455188), [2010](https://economics.mit.edu/files/11859), [2015](https://onlinelibrary.wiley.com/doi/abs/10.1111/ajps.12116) for more on the method and use cases.
Building on the [`Synth`](https://CRAN.R-project.org/package=Synth) package, `tidysynth` makes a number of improvements when implementing the method in `R`. These improvements allow users to inspect, visualize, and tune the synthetic control more easily. A key benefit of a tidy implementation is that the entire preparation process for building the synthetic control can be accomplished in a single pipe.
Specifically, the package:
- generates placebo synthetic controls on the fly allowing for inferential statistics;
- offers plotting methods to easily explore the fit of the synthetic control and weights;
- increases transparency and usability through a pipe-able implementation;
- relies on a nested tidy data structure with `grab_` prefix functions to easily extract component elements from synthetic control pipeline.
## Installation
Cran.
```{r,eval=F}
install.packages('tidysynth')
```
Developer Version.
```{r,eval=F}
# install.packages("devtools")
devtools::install_github("edunford/tidysynth")
```
## Usage
The package uses a pipeline of functions to generate the synthetic control.
| Function | Description
|:---------|:----------|
| `synthetic_control()` | Initialize a synth pipeline by specifying the panel series, outcome, and intervention period. This pipeline operates as a nested `tbl_df` |
| `generate_predictor()` | Create one or more scalar variables summarizing covariate data across a specified time window. These predictor variables are used to fit the synthetic control. |
| `generate_weights()` | Fit the unit and predictor weights used to generate the synthetic control. |
| `generate_control()` | Generate the synthetic control using the optimized weights. |
The following example comes from [Abadie et al. 2010](https://economics.mit.edu/files/11859), which evaluates the impact of Proposition 99 on cigarette consumption in California.
```{r,message=F}
require(tidysynth)
data("smoking")
smoking %>% dplyr::glimpse()
```
The method aims to generate a synthetic California using information from a subset of control states (the "donor pool") where a similar law was _not_ implemented. The donor pool is the subset of case comparisons from which information is borrowed to generate a synthetic version of the treated unit ("California").
```{r,cache=T}
smoking_out %
# initial the synthetic control object
synthetic_control(outcome = cigsale, # outcome
unit = state, # unit index in the panel data
time = year, # time index in the panel data
i_unit = "California", # unit where the intervention occurred
i_time = 1988, # time period when the intervention occurred
generate_placebos=T # generate placebo synthetic controls (for inference)
) %>%
# Generate the aggregate predictors used to fit the weights
# average log income, retail price of cigarettes, and proportion of the
# population between 15 and 24 years of age from 1980 - 1988
generate_predictor(time_window = 1980:1988,
ln_income = mean(lnincome, na.rm = T),
ret_price = mean(retprice, na.rm = T),
youth = mean(age15to24, na.rm = T)) %>%
# average beer consumption in the donor pool from 1984 - 1988
generate_predictor(time_window = 1984:1988,
beer_sales = mean(beer, na.rm = T)) %>%
# Lagged cigarette sales
generate_predictor(time_window = 1975,
cigsale_1975 = cigsale) %>%
generate_predictor(time_window = 1980,
cigsale_1980 = cigsale) %>%
generate_predictor(time_window = 1988,
cigsale_1988 = cigsale) %>%
# Generate the fitted weights for the synthetic control
generate_weights(optimization_window = 1970:1988, # time to use in the optimization task
margin_ipop = .02,sigf_ipop = 7,bound_ipop = 6 # optimizer options
) %>%
# Generate the synthetic control
generate_control()
```
Once the synthetic control is generated, one can easily assess the fit by comparing the trends of the synthetic and observed time series. The idea is that the trends in the pre-intervention period should map closely onto one another.
```{r,fig.align="center",fig.width=10,fig.height=5,dpi=300}
smoking_out %>% plot_trends()
```
To capture the causal quantity (i.e. the difference between the observed and counterfactual), one can plot the differences using `plot_differences()`
```{r,fig.align="center",fig.width=10,fig.height=5,dpi=300}
smoking_out %>% plot_differences()
```
In addition, one can easily examine the weighting of the units and variables in the fit. This allows one to see which cases were used, in part, to generate the synthetic control.
```{r,fig.align="center",fig.width=10,fig.height=5,dpi=300}
smoking_out %>% plot_weights()
```
Another useful way of evaluating the synthetic control is to look at how comparable the synthetic control is to the observed covariates of the treated unit.
```{r}
smoking_out %>% grab_balance_table()
```
### Inference
For inference, the method relies on repeating the method for every donor in the donor pool exactly as was done for the treated unit — i.e. generating _placebo_ synthetic controls). By setting `generate_placebos = TRUE` when initializing the synth pipeline with `synthetic_control()`, placebo cases are automatically generated when constructing the synthetic control of interest. This makes it easy to explore how unique difference between the observed and synthetic unit is when compared to the placebos.
```{r,fig.align="center",fig.width=10,fig.height=5,dpi=300}
smoking_out %>% plot_placebos()
```
Note that the `plot_placebos()` function automatically prunes any placebos that poorly fit the data in the pre-intervention period. The reason for doing so is purely visual: those units tend to throw off the scale when plotting the placebos. To prune, the function looks at the pre-intervention period mean squared prediction error (MSPE) (i.e. a metric that reflects how well the synthetic control maps to the observed outcome time series in pre-intervention period). If a placebo control has a MSPE that is two times beyond the target case (e.g. "California"), then it's dropped. To turn off this behavior, set `prune = FALSE`.
```{r,fig.align="center",fig.width=10,fig.height=5,dpi=300}
smoking_out %>% plot_placebos(prune = FALSE)
```
Finally, Adabie et al. 2010 outline a way of constructing Fisher's Exact P-values by dividing the post-intervention MSPE by the pre-intervention MSPE and then ranking all the cases by this ratio in descending order. A p-value is then constructed by taking the rank/total.^[Note this implies that you'd need at least 20 cases in the donor pool to get a conventional p-value (.05).] The idea is that if the synthetic control fits the observed time series well (low MSPE in the pre-period) and diverges in the post-period (high MSPE in the post-period) then there is a meaningful effect due to the intervention. If the intervention had no effect, then the post-period and pre-period should continue to map onto one another fairly well, yielding a ratio close to 1. If the placebo units fit the data similarly, then we can't reject the hull hypothesis that there is no effect brought about by the intervention.
This ratio can be easily plotted using `plot_mspe_ratio()`, offering insight into the rarity of the case where the intervention actually occurred.
```{r,fig.align="center",fig.width=10,fig.height=5,dpi=300}
smoking_out %>% plot_mspe_ratio()
```
For more specific information, there is a significance table that can be extracted with one of the many `grab_` prefix functions.
```{r}
smoking_out %>% grab_signficance()
```
### Accessing Data
In addition to the main data pipeline for generating the synthetic control and the `plot_` prefix functions for visualizing the output, there are a number of `grab_` prefix functions that offer easy access to the data contained within a synth pipeline object.
At its core, a synth pipeline is simply a nested tibble data frame, where each component of the synthetic control pipeline is accessible.
```{r}
smoking_out
```
To access the relevant data fields, the `grab_` prefix functions come into play.
| Function | Description |
|:------------------|:--------------------|
| `grab_outcome()` | Extract the outcome variable generated by `synthetic_control()`. |
| `grab_predictors()` | Extract the aggregate-level covariates generated by `generate_predictor()`. |
| `grab_unit_weights()` | Extract the unit weights generated by `generate_weights()`. |
| `grab_predictor_weights()` | Extract the predictor variable weights generated by `generate_weights()`. |
| `grab_loss()` | Extract the RMSE loss of the optimized weights generated by `generate_weights()`. |
| `grab_synthetic_control()` | Extract the synthetic control generated using `generate_control()`. |
| `grab_signficance()` | Generate inferential statistics comparing the rarity of the unit that actually received the intervention to the placebo units in the donor pool. |
| `grab_balance_table()` | Compare the distributions of the aggregate-level predictors for the observed intervention unit, the synthetic control, and the donor pool average. |
```{r}
smoking_out %>% grab_synthetic_control()
```
Note that most all the `grab_` functions allow for extraction of the placebo units as well.
```{r}
smoking_out %>% grab_synthetic_control(placebo = T)
```
#### But say I really want to `unnest()`...
In the current implementation, you can unpack an entire synth pipeline using `unnest()`. The `grab_` function is meant to streamline any specific extraction needs. The entire method is built on top of a tidyverse infrastructure, so one can side-step most of the package's functionality and interact with the synth pipeline output as one would any nested `tbl_df` object.
```{r}
smoking_out %>%
tidyr::unnest(cols = c(.outcome))
```
## Debugging
Spot an issue? Please let me know by posting an issue.