---
title: "Multiple Treated"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Multiple Treated}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  echo = TRUE,
  warning = FALSE,
  message = FALSE,
  out.width = '90%', 
  out.height = '600px',
  fig.align='center'
)
set.seed(123)
```

## Background

In this vignette I show how {bsynth} can be used for causal estimation when you 
 have multiple treated accounts. In particular, I use the synthetic data exaple
 from [Xu, Yiqing, 2017](http://dx.doi.org/10.1017/pan.2016.2). In this example,
 the treatment starts in period 21 and increases by one each period 
 (e.g. the effect is 5 period 25 and 10 in period 30).
 
```{r original_figure, echo = FALSE, fig.cap = "Figure 1: Xu, Yiqing, 2017", out.height = '400px'}
knitr::include_graphics(path = "https://ignacio.martinez.fyi/synthetic_control/gsynth.png")

```

## Bayesian Synthetic Control with Covariates

```{r setup, out.height = '800px'}
library(bsynth)
ci_width <- 0.95
data(gsynth, package = "gsynth")
dplyr::glimpse(simdata)

outcome_data <- simdata %>% 
  dplyr::select(time, id, D, Y)

covariates <- simdata %>% 
  dplyr::select(time, id, X1, X2)

synth <-
  bsynth::bayesianSynth$new(
    data = outcome_data,
    time = time,
    id = id,
    treated = D,
    outcome = Y, 
    ci_width = ci_width,
    covariates = covariates
  )

synth$timeTiles +
  ggplot2::theme(text = ggplot2::element_text(size=6))

```

### Fit

```{r fit, results="hide"}
synth$fit()
```

### Visualize the synthetic controls for each treated unit

```{r}
synth$synthetic  
```
### Visualize the treatment effect

```{r}
synth$effectPlot(subset = c("Average"), facet = FALSE) + 
  ggplot2::scale_y_continuous(breaks=seq(-2,12,2))
```
