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

```{r setup, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)

library(aggTrees)
library(grf)
```

In this tutorial, we show how to use the `aggTrees` package to discover heterogeneous subgroups in a selection-on-observables setting. 

## Methodology Overview
The approach consists of three steps:

1. Estimate the conditional average treatment effects (CATEs);
2. Approximate the CATEs by a decision tree;
3. Prune the tree.

This way, we generate a sequence of groupings, one for each granularity level. 

The resulting sequence is nested in the sense that subgroups formed at a given level of granularity are never broken at coarser levels. This guarantees consistency of the results across the different granularity levels, generally considered a basic requirement that every classification system should satisfy. Moreover, each grouping features an optimality property in that it ensures that the loss in
explained heterogeneity resulting from aggregation is minimized.

Given the sequence of groupings, we can estimate the group average treatment effects (GATEs) as we like. The package supports two estimators, based on differences in mean outcomes between treated and control units (unbiased only in randomized experiments) and on debiased machine learning procedures (unbiased also in observational studies). 

The package also allows to get standard errors for the GATEs by estimating via OLS appropriate linear models. Then, under an "honesty" condition, we can use the estimated standard errors to conduct valid inference about the GATEs as usual, e.g., by constructing conventional confidence intervals.[^1]

## Code
For illustration purposes, let us generate some data. We also split the observed sample into a training sample and an honest sample of equal sizes, as this will be necessary to achieve valid inference about the GATEs later on.

```{r data-generation, eval = TRUE}
## Generate data.
set.seed(1986)

n <- 500 # Small sample size due to compliance with CRAN notes.
k <- 3

X <- matrix(rnorm(n * k), ncol = k)
colnames(X) <- paste0("x", seq_len(k))
D <- rbinom(n, size = 1, prob = 0.5)
mu0 <- 0.5 * X[, 1]
mu1 <- 0.5 * X[, 1] + X[, 2]
Y <- mu0 + D * (mu1 - mu0) + rnorm(n)

## Sample split.
splits <- sample_split(length(Y), training_frac = 0.5)
training_idx <- splits$training_idx
honest_idx <- splits$honest_idx

Y_tr <- Y[training_idx]
D_tr <- D[training_idx]
X_tr <- X[training_idx, ]

Y_hon <- Y[honest_idx]
D_hon <- D[honest_idx]
X_hon <- X[honest_idx, ]
```

### CATEs Estimation
First, we need to estimate the CATEs. This can be achieved with any estimator we like. Here we use the causal forest estimator. The CATEs are estimated using only the training sample.

```{r estimate-cates, eval = TRUE}
## Estimate the CATEs. Use only training sample.
forest <- causal_forest(X_tr, Y_tr, D_tr) 

cates_tr <- predict(forest, X_tr)$predictions
cates_hon <- predict(forest, X_hon)$predictions
```

### Constructing the Sequence of Groupings
Now we use the `build_aggtree` function to construct the sequence of groupings. This function approximates the estimated CATEs by a decision tree using only the training sample and computes node predictions (i.e., the GATEs) using only the honest sample. `build_aggtree` allows the user to choose between two GATE estimators:

1. If we set `method = "raw"`, the GATEs are estimated by taking the differences between the mean outcomes of treated and control units in each node. This is an unbiased estimator (only) in randomized experiments;
2. If we set `method = "aipw"`, the GATEs are estimated by averaging doubly-robust scores in each node. This is an unbiased estimator also in observational studies under particular conditions on the construction of the scores.[^2]

The doubly-robust scores are estimated internally using 5-fold cross-fitting and only observations from the honest sample.

```{r construct-sequence, eval = TRUE}
## Construct the sequence. Use doubly-robust scores (default option).
groupings <- build_aggtree(Y_tr, D_tr, X_tr, # Training sample. 
                           Y_hon, D_hon, X_hon, # Honest sample.
                           cates_tr = cates_tr, cates_hon = cates_hon) # Predicted CATEs.

## Print.
print(groupings)

## Plot.
plot(groupings) # Try also setting 'sequence = TRUE'.
```

### Further Analysis
Now that we have a whole sequence of optimal groupings, we can pick the grouping associated with our preferred granularity level and call the `inference_aggtree` function. This function does the following:

1. It gets standard errors for the GATEs by estimating via OLS appropriate linear models using the honest sample. The choice of the linear model depends on the `method` we used when we called `build_aggtree`;[^3]
2. It tests the null hypotheses that the differences in the GATEs across all pairs of groups equal zero. Here, we account for multiple hypotheses testing by adjusting the $p$-values using Holm's procedure;
3. It computes the average characteristics of the units in each group.

To report the results, we can print nice LATEX tables.

```{r inference, eval = TRUE}
## Inference with 4 groups.
results <- inference_aggtree(groupings, n_groups = 4)

## LATEX.
print(results, table = "diff")

print(results, table = "avg_char")
```

[^1]: Check the [inference vignette](https://riccardo-df.github.io/aggTrees/articles/inference.html) for more details. 
[^2]: See footnote 1.
[^3]: See footnote 1.
