Counterfactual: An R Package for Counterfactual Analysis

The Counterfactual package implements the estimation and inference methods of (Cher-nozhukov et al., 2013) for counterfactual analysis. The counterfactual distributions considered are the result of changing either the marginal distribution of covariates related to the outcome variable of interest, or the conditional distribution of the outcome given the covariates. They can be applied to estimate quantile treatment effects and wage decompositions. This paper serves as an introduction to the package and displays basic functionality of the commands contained within.


Introduction
Using econometric terminology, we can often think of a counterfactual distribution as the result of a change in either the distribution of a set of covariates X that determine the outcome variable of interest Y, or the relationship of the covariates with the outcomes, that is, a change in the conditional distribution of Y given X. Counterfactual analysis consists of evaluating the effects of such changes. The Counterfactual package implements the methods of (Chernozhukov et al., 2013) for counterfactual analysis. It contains commands to estimate and make inference on quantile effects constructed from counterfactual distributions. The counterfactual distributions are estimated using regression methods such as classical, duration, quantile and distribution regressions. The inference on the quantile effect function can be pointwise at a specific quantile index or uniform over a range of specified quantile indexes.
We start by giving a simple example of counterfactual analysis. Suppose we would like to analyze the wage differences between men and women. Let 0 denote the population of men and let 1 denote the population of women. The variable Y j denotes wages and X j denotes job market-relevant characteristics that affect wages for populations j = 0 and j = 1. The conditional distribution functions F Y 0 |X 0 (y|x) and F Y 1 |X 1 (y|x) describe the stochastic assignment of wages to workers with characteristics x, for men and women, respectively. Let F Y 0|0 and F Y 1|1 represent the observed distribution function of wages for men and women, and let F Y 0|1 represent the distribution function of wages that would have prevailed for women had they faced the men's wage schedule F Y 0 |X 0 : The latter distribution is called counterfactual, since it does not arise as a distribution from any observable population. Rather, this distribution is constructed by integrating the conditional distribution of wages for men with respect to the distribution of characteristics for women. This quantity is well defined if X 0 , the support of men's characteristics, includes X 1 , the support of women's characteristics, namely X 1 ⊂ X 0 .
Let F ← denote the quantile or left-inverse function of the distribution function F. The difference in the observed wage quantile function between men and women can be decomposed in the spirit of (Oaxaca, 1973) and (Blinder, 1973) as where the first term in brackets is due to differences in the wage structure and the second term is a composition effect due to differences in characteristics. These counterfactual effects are well defined econometric parameters and are widely used in empirical analysis, for example, the first term of the decomposition is a measure of gender wage discrimination. In Section 2.3.2 we consider an empirical example where 0 denotes the population of nonunion workers and 1 denotes the population of union workers. In this case the the wage structure effect corresponds to the treatment effect of union or union premium. It is important to note that these effects do not necessarily have a causal interpretation without additional conditions that are spelled out in (Chernozhukov et al., 2013). To describe the different options of the command we need to provide some background on methods for counterfactual analysis.

Setting for counterfactual analysis
Consider a general setting with two populations labeled by k ∈ K = {0, 1}. For each population k there is the d x -vector X k of covariates and the scalar outcome Y k . The covariate vector is observable in all populations, but the outcome is only observable in populations j ∈ J ⊆ K. Let F X k denote the covariate distribution in population k ∈ K, and F Y j |X j and Q Y j |X j denote the conditional distribution and quantile functions in population j ∈ J . We denote the support of X k by X k ⊆ R d x , and the region of interest for Y j by Y j ⊆ R. The refer to j as the reference population(s) and to k as the counterfactual population(s).
The reference and counterfactual populations in the wage examples correspond to different groups such as men and women or nonunion and union workers. We can also generate counterfactual populations by artificially transforming a reference population. Formally, we can think of X k as being created through a known transformation of X j : This case covers adding one unit to the first covariate, X 1,k = X 1,j + 1, holding the rest of the covariates constant. The resulting quantile effect becomes the unconditional quantile regression, which measures the effect of a unit change in a given covariate component on the unconditional quantiles of Y. For example, this type of counterfactual is useful for estimating the treatment effect of smoking during pregnancy on infant birth weights. Another possible transformation is a mean preserving redistribution of the first covariate implemented as X 1,k = (1 − α)E[X 1,j ] + αX 1,j . These and more general types of transformation defined in (2) are useful for estimating the effect of a change in taxation on the marginal distribution of food expenditure or the effect of cleaning up a local hazardous waste site on the marginal distribution of housing prices ( (Stock, 1991)). We give an example of this type of transformation in Section 2.3.1.
The reference and counterfactual populations can be specified to counterfactual in two ways that accommodate the previous two cases: 1. If the option group has been specified, then j is the population defined by group and k is the population defined by group=1. This means that both X and Y are observed in group=0, but only X needs to be observed in group=1. When both X and Y are observed in group=1, the option treatment=TRUE specifies that the structure or treatment effect should be computed, whereas the default option treatment=FALSE specifies that the composition effect should be computed; see the definition of the structure and composition effects in the decomposition (1). If in addition to treatment=TRUE the option decomposition=TRUE is selected, then the entire decomposition (1) is reported including the composition, structure and total effects. Note that we can reverse the roles of the populations defined by an indicator variable vargroup by setting either group=vargroup or group=1-vargroup.
2. Alternatively, the option counterfactual_var can be used to specify the covariates in the counterfactual population. In this case, the names on the right handside of formula contain the variables in X j and counterfactual_var contains the variables in X k . The option transformation=TRUE should be used when X k is generated as a transformation of X j , e.g., equation (2). The list passed to counterfactual_var must contain exactly the same number of variables as the list of independent variables in formula and the order of the variables in the list matters.
Counterfactual distribution and quantile functions are formed by combining the conditional distribution in the population j with the covariate distribution in the population k, namely: The main interest lies in the quantile effect (QE) function, defined as the difference of two counterfactual quantile functions over a set of quantile indexes T ⊂ (0, 1): where j ∈ J and k ∈ K. In the example of Section 2.1, we obtain the composition effect with j = 0 and k = 1. When Y k is observed, then we can construct the structure effect or treatment effect on the treated by specifying the option group and setting treatment=TRUE. In the example of Section 2.1, we obtain the wage structure effect with j = 0 and k = 1, i.e. setting group=1 and treatment=TRUE. If in addition we select the option decomposition=TRUE, then we obtain the entire decomposition (1) including the composition, structure and total effects. The total effect is The set T is specified with the option quantiles, which enumerates the quantile indexes of interested and should be a vector containing numbers between 0 and 1.
To estimate the QE function we need to model and estimate the conditional distribution F Y j |X j and covariate distribution F X k . We estimate the covariate distribution using the empirical distribution, and consider several regression based methods for the conditional distribution including classical, quantile, duration, and distribution regression. Given the estimators of the conditional and covariate distributionsF Y j |X j andF X k , the estimator of each counterfactual distribution is obtained by the plug-in rule, namelyF Then, the estimator of the QE function is also obtained by the plug-in rule aŝ if we define the counterfactual population with group and set treatment=TRUE. If in addition to treatment=TRUE, we select decomposition=TRUE, then the plug-in estimator of the total effect iŝ

Estimation of conditional distribution
In this section we assume that we have samples {(Y ji , X ji ) : i = 1, . . . , n j } composed of independent and identically distributed copies of (Y j , X j ) for all populations j ∈ J . The conditional distribution F Y j |X j can be modeled and estimated directly, or throught the conditional quantile function, Q Y j |X j , using the relation The option formula specifies the outcome Y as the left hand side variable and the covariates X as the right hand side variable(s). The option method allows to select the method to estimate the conditional distribution. The following methods are implemented: 1. method = "qr", which is the default, implements the quantile regresion estimator of the conditional distributionF where ε is a small constant that avoids estimation of tail quantiles, andβ(u) is the (Koenker and Bassett, 1978) quantile regression estimator The quantile regression estimator calls the R package quantreg (Koenker, 2016). The option trimming specifies the value of the trimming parameter ε, with default value ε = 0.005. The option nreg sets the number of quantile regressions used to approximate the integral in (4), with a default value of 100 such that (ε, This method should be used only with continuous dependent variables.
2. method = "loc" implements the estimator of the conditional distribution whereβ j is the least square estimator The estimator (5) is based on a restrictive location shift model that imposes that the covariates X only affect the location of the outcome Y.
3. method = "locsca" implements the estimator of the conditional distribution whereβ j is the least square estimator (6), X 2j ⊆ X j with dim X 2j = d x 2 , and The option scale_variable specifies the covariates X 2j that affect the scale of the conditional distribution. The option counterfactual_scale_variable selects the counterfactual scale variables when the counterfactual population is specified using counterfactual_var. By default, R would use all the covariates as scale_variable and counterfactual_scale_variable = counterfactual_var. The estimator (7) is based on a restrictive location scale shift model that imposes that the covariates X only affect the location and scale of the outcome Y.
4. method = "cqr" implements the censored quantile regression estimator of the conditional distribution, which is the same as (4) withβ(u) replaced by the (Chernozhukov and Hong, 2002) censored quantile regression estimator. The options trimming and nreg apply to this method with the same functionality as for the qr method. Moreover, a variable containing a censoring indicator C j must be specified with censoring. The censored quantile regression estimator has three-steps by default. The number of steps can be increased by the option nsteps. In the first step, the censoring probabilities are estimated by a logit regression of the censoring indicator C j on all the covariates X j . Then, for each quantile index u, the observations with sufficiently low censoring probabilities relative to u are selected. We allow for misspecification of the logit by excluding the observations that could theoretically be used but have censoring probabilities in the highest firstc quantiles, with a default of 0.1, i.e. 10% of the observations. In the second step, standard linear quantile regressions are estimated on the samples defined in step one.
Using the estimated quantile regressions, we define a new sample of observations that can be used. This sample consists of all observations for which the estimated conditional quantile is above the censoring point. Again, we throw away observations in the lowest secondc quantiles of the distribution of the residuals, with a default of 0.05, i.e. 5% of the observations.
Step three consists in a new linear quantile regression using the sample defined in step two.
Step three is repeated if nsteps is above 3. This method should be used only with censored dependent variables.
5. method = "cox" implements the duration regression estimator of the conditional distribution functionF whereβ is the Cox estimator of the regression coefficients andt(y) is the Cox estimator of the baseline integrated hazard function (Cox, 1972). The Cox estimator calls the R package survival (Therneau, 2015). The estimator (8) is based on a restrictive transformation location shift model that imposes that the covariates X only affect the location of a monotone transformation of the where V j has an extreme value distribution and is independent of X j . This method should be used only with nonnegative dependent variables.
6. method = "logit" implements the distribution regression estimator of the conditional distribution with logistic link functionF where Λ is the standard logistic distribution function, andβ(y) is the distribution regression estimatorβ The estimator (9) is based on a flexible model where each covariate can have a heterogenous effect at different parts of the distribution. This method can be used with continuous dependent variables and censored dependent variables with fixed censoring point.
7. method = "probit" implements the distribution regression estimator of the conditional distribution with normal link function, i.e. where Λ is the standard normal distribution function in (9) and (10).
8. method = "lpm" implements the linear probability model estimator of the conditional distribution whereβ(y) is the least squares estimator This method might produce estimates of the conditional distribution outside the interval [0, 1].
For the methods (2)-(8), the option nreg sets the number of values of y to evaluate the estimator of the conditional distribution function. These values are uniformly distributed among the observed values of Y j . If nreg is greater than the number of observed values of Y j , then all the observed values are used.

Inference
The command counterfactual reports pointwise and uniform confidence intervals for the QEs over a prespecified set of quantile indexes. The construction of the intervals rely on functional central limit theorems and bootstrap functional central limit theorems for the empirical QEs derived in (Chernozhukov et al., 2013). In particular, the pointwise intervals are based on the normal distribution, whereas the uniform intervals are based on two resampling schemes: empirical and weighted bootstrap. Thus, the (1 − α) confidence interval for ∆(τ) on T has the form {∆(τ) ± c 1−αΣ (τ) : τ ∈ T }, whereΣ(τ) is the standard error of∆(τ) and c 1−α is a critical value. There are two options to obtain Σ(τ). The default option robust=FALSE computes the bootstrap standard deviation of∆(τ); whereas the option robust=TRUE computes the bootstrap interquartile range rescaled with the normal distribution,Σ(τ) = (q 0.75 (τ) − q 0.25 (τ))/(z 0.75 − z 0.25 ) where q p (τ) is the pth quantile of the bootstrap draws of∆(τ) and z p is the pth quantile of the standard normal. The pointwise critical value is c 1−α = z 1−α , and the uniform critical value is c 1−α =t 1−α , wheret 1−α is a bootstrap estimator of the (1 − α)th quantile of the Kolmogorov-Smirnov maximal t-statistic In addition to the intervals, counterfactual reports the p-values for several functional tests based on two test-statistic: Kolmogorov-Smirnov and the Cramer-von-Misses-Smirnov. The null-hypotheses considered are 1. Correct parametric specification of the model for the conditional distribution. This test compares the empirical distribution of the outcome Y j with the estimate of the counterfactual distribution in the reference populationF The power of this specification test might be low because it only uses the implications of the conditional distribution on the counterfactual distribution. For example, the test is not informative for the linear probability and logit models where the counterfactual distribution in the reference population is identical to the empirical distribution by construction. If group is specified and treatment=TRUE is selected, then the test is performed in the population defined by group=1. If in addition the option decomposition=TRUE is selected, then the test is performed in the populations defined by group=0 and group=1, and in the combined population including both group=0 and group=1.
2. Zero QE at all the quantile indexes of interest: ∆(τ) = 0 for all τ ∈ T . This is stronger than a zero average effect. Other null hypotheses of constant quantile effect (but at a different level than 0) can be added with the option cons_test.
The options of counterfactual related to inference are: 1. noboot = TRUE suppresses the bootstrap. The bootstrap can be very demanding in terms of computation time. Therefore, it is recommended to switch it off for the exploratory analysis of the data.
2. weightedboot = TRUE selects weighted bootstrap with standard exponential weights. The default weightedboot = FALSE selects empirical bootstrap with multinomial weights. We recommend weighted bootstrap when the covariates include categorical variables with small cell sizes to avoid singular designs in the bootstrap draws.
3. reps specifies the number of bootstrap replications. This number will matter only if the bootstrap has not be suppressed. The default is 100.
4. alpha specifies the significance level of the tests and confidence intervals. Note that the confidence level of the confidence interval is 1 -alpha. Thus, the default value of 0.05 produces 95% confidence intervals.
5. first and last select the subset of quantile indexes of interest for inference. The tails of the distribution should not be used because standard asymptotic does not apply to these parts. The needed amount of tail trimming depends on the sample size and on the distribution of the dependent variable. first sets the lowest quantile index used and last sets the highest quantile index used. The default values are 0.1 and 0.9 so that T = [0.1, 0.9].
6. cons_test add tests of the null hypothesis that ∆(τ) = const_test for all τ between first and last. The null hypothesis that ∆(τ) = 0 for all τ between first and last is tested by default. The null hypothesis that the quantile effects are constant is also tested by default.

Parallel computing
The command counterfactual provides functionality for parallel computing, which is specially useful to speed up the execution of the bootstrap. There are two options related to parallel computing: 1. setcore specifies whether multiple cores should be used. The default value setcore = FALSE turns off the parallel computing.
2. ncore selects the number of cores to use for parallel computing. The information of this option is only used when parallel computing is switched on with setcore = TRUE.

Empirical examples
We consider two empirical examples to illustrate the functionality of the command counterfactual.
The first example is an estimation of Engel curves that includes a counterfactual analysis where the counterfactual population is an artificial transformation of a reference population. The second example is wage decomposition with respect to union status where the reference and counterfactual populations correspond to two different groups.

Engel curves
We use the classical Engel 1857 dataset to estimate the relationship between food expenditure (foodexp) and annual household income (income), and then report the estimates of the QE of a change in the distribution of the annual household income that might be induced for example by a variation in income taxation. 1 We estimate the conditional distribution with the quantile regression method, i.e., method ="qr".
First, we generate the variable counterfactual_income with the counterfactual values of income and plot the reference and counterfactual income distributions. The counterfactual distribution corresponds to a mean preserving spread of the distribution in the reference population that reduces standard deviation by 25%.
Finally, we reestimate the QE function on the larger set of quantiles {0.01, 0.02, . . . , 0.99}, and plot a uniform confidence band over the subset {0.10, 0.11, . . . , 0.90} constructed by empirical bootstrap with 100 replications. In Figure 2 we can visually reject the functional hypotheses of zero, constant, positive and negative effect at the percentiles considered. We use the option printdeco = FALSE to suppress the display of the table of results.

Union premium
We use an extract of the U.S. National Longitudinal Survey of Young Women (NLSW) for employed women in 1988 to estimate a wage decomposition with respect to union status. 2 The outcome variable Y is the log hourly wage (lwage), the covariates X include job tenure in years (tenure), years of schooling (grade), and total experience (ttl_exp), and the union indicator union defines the reference and counterfactual populations. We estimate the conditional distributions by distribution regression with logistic link and duration regression, i.e., method ="logit" and method ="cox". We use weighted bootstrap for the construction of uniform confidence intervals and hypothesis tests and run parallel computing with 2 nodes.
We start by estimating the wage decomposition by logistic distribution regression, where the counterfactual population is specified with group=union with the options treatment=TRUE and decom-position=TRUE to estimate the composition, structure and total effects. The structure effect in this case correspond to the treatment effect of union on the treated or union premium. The tables show that the union workers earn higher wages than the nonumion workers throuoghout the distribution although the union wage gap is decreasing in the quantile index. This gap can be mostly explained by differences in tenure, education and experience between union and nonunion workers in the upper tail of the distribution and by the union premium in the rest of the distribution.
No. of obs. in the reference group:   Figure 3 shows that the structure effect is heterogeneous across the quantile indexes and explains most of the union wage gap below the third quartile. The composition effect is constant across quantile indexes and explains most of the wage gap above the third quartile.