40  Stata 19 CATE command

Published

June 26, 2025

40.1 Stata 19 CATE command

Stata 19 introduces a cate command for estimating conditional average treatment effects (CATE). Fernando Rios-Avila provides an overview.

The Stata chunks below are cached (cache: true) because the cate command does lasso cross-fitting plus a random forest, and a full re-execution of this chapter takes over five minutes. The cache is safe for prose edits, which leave every chunk served uniformly from cache. It is not safe if you edit the code of one Stata chunk: the edited chunk re-executes while the earlier collectcode: true chunks are still served from cache, their code never enters Statamarkdown’s accumulated buffer, every command runs against missing data, and the chunk renders silently blank – and that empty result is then cached in turn.

If that happens, delete stata-cate_cache/ entirely (not just the offending chunk’s entry) along with _freeze/stata-cate/, then re-render so all chunks run in order. Clearing _freeze/ alone is not enough. See the note in this book’s CLAUDE.md.

Code
clear all
webuse assets3
global catecovars age educ i.(incomecat pension married twoearn ira ownhome)
cate po (assets $catecovars) (e401k), group(incomecat) nolog
(Excerpt from Chernozhukov and Hansen (2004))



Conditional average treatment effects     Number of observations       = 9,913
Estimator:       Partialing out           Number of folds in cross-fit =    10
Outcome model:   Linear lasso             Number of outcome controls   =    17
Treatment model: Logit lasso              Number of treatment controls =    17
CATE model:      Random forest            Number of CATE variables     =    17

------------------------------------------------------------------------------
             |               Robust
      assets | Coefficient  std. err.      z    P>|z|     [95% conf. interval]
-------------+----------------------------------------------------------------
GATE         |
   incomecat |
          0  |   3999.888   989.8742     4.04   0.000      2059.77    5940.006
          1  |   1424.931   1668.081     0.85   0.393    -1844.447     4694.31
          2  |   5092.801   1344.769     3.79   0.000     2457.102    7728.499
          3  |   8700.512   2272.126     3.83   0.000     4247.226     13153.8
          4  |   20350.97   4717.093     4.31   0.000     11105.64     29596.3
-------------+----------------------------------------------------------------
ATE          |
       e401k |
  (Eligible  |
         vs  |
Not elig..)  |    7914.24    1150.79     6.88   0.000     5658.734    10169.75
-------------+----------------------------------------------------------------
POmean       |
       e401k |
Not eligi..  |   14012.54   834.0963    16.80   0.000     12377.74    15647.34
------------------------------------------------------------------------------

The data are assets3, from Chernozhukov and Hansen (2004): 9,913 households, with net financial assets as the outcome and 401(k) eligibility as the treatment. The group ATEs by income category show strong heterogeneity — $4,000 in the lowest category, $1,425 in the second (not significant), then $5,093, $8,701 and $20,350 as income rises. A single ATE would hide a fivefold spread.

He said “We can achieve comparable results using standard regression with full interactions:”

Code
clear all
webuse assets3
global catecovars age educ i.(incomecat pension married twoearn ira ownhome)

* you do not want to see all interactions.
qui:reg assets i.incomecat##i.e401k##c.($catecovars), robust

* Average Treatment Effect (ATE)
margins, at(e401k=(0 1)) noestimcheck contrast(atcontrast(r))

* Group Average Treatment Effects (GATEs)
margins, at(e401k=(0 1)) noestimcheck contrast(atcontrast(r)) over(incomecat)
(Excerpt from Chernozhukov and Hansen (2004))




Contrasts of predictive margins                          Number of obs = 9,913
Model VCE: Robust

Expression: Linear prediction, predict()
1._at: e401k = 0
2._at: e401k = 1

------------------------------------------------
             |         df           F        P>F
-------------+----------------------------------
         _at |          1       44.72     0.0000
             |
 Denominator |       9833
------------------------------------------------

--------------------------------------------------------------
             |            Delta-method
             |   Contrast   std. err.     [95% conf. interval]
-------------+------------------------------------------------
         _at |
   (2 vs 1)  |   7642.407   1142.797      5402.291    9882.524
--------------------------------------------------------------


Contrasts of predictive margins                          Number of obs = 9,913
Model VCE: Robust

Expression: Linear prediction, predict()
Over:       incomecat
1._at: 0.incomecat
           e401k = 0
       1.incomecat
           e401k = 0
       2.incomecat
           e401k = 0
       3.incomecat
           e401k = 0
       4.incomecat
           e401k = 0
2._at: 0.incomecat
           e401k = 1
       1.incomecat
           e401k = 1
       2.incomecat
           e401k = 1
       3.incomecat
           e401k = 1
       4.incomecat
           e401k = 1

-------------------------------------------------
              |         df           F        P>F
--------------+----------------------------------
_at@incomecat |
  (2 vs 1) 0  |          1       16.08     0.0001
  (2 vs 1) 1  |          1        0.67     0.4123
  (2 vs 1) 2  |          1       16.03     0.0001
  (2 vs 1) 3  |          1       13.77     0.0002
  (2 vs 1) 4  |          1       17.26     0.0000
       Joint  |          5       12.76     0.0000
              |
  Denominator |       9833
-------------------------------------------------

---------------------------------------------------------------
              |            Delta-method
              |   Contrast   std. err.     [95% conf. interval]
--------------+------------------------------------------------
_at@incomecat |
  (2 vs 1) 0  |   3594.182   896.3298      1837.191    5351.172
  (2 vs 1) 1  |     1283.3   1565.151     -1784.718    4351.317
  (2 vs 1) 2  |   5056.144   1262.728      2580.938     7531.35
  (2 vs 1) 3  |   8610.622   2320.156      4062.641     13158.6
  (2 vs 1) 4  |   19665.61   4733.551      10386.88    28944.34
---------------------------------------------------------------

Numerically these two sets of estimations may be close, but I don’t think they are from the same model, even the same idea. The CATE command with “PO” option is to estimate the CATE with “partialling out” approach.

What Fernando did is a “regression adjustment” type of model, which is modeling outcome model and allow interaction of treatment and covariates. The “partialling out” approach is sometimes called double ML.

Let’s see how to replicate “teffects ra” with “reg”:

Code
clear all
webuse assets3
global catecovars age educ i.(incomecat pension married twoearn ira ownhome)

teffects ra (assets age educ i.(incomecat pension married twoearn ira ownhome))(e401k)

qui: reg assets i.e401k##c.(age educ) i.e401k##i.(incomecat pension married twoearn ira ownhome)
margins, at(e401k=(0 1)) noestimcheck contrast(atcontrast(r))
(Excerpt from Chernozhukov and Hansen (2004))



Iteration 0:  EE criterion = 1.291e-21  
Iteration 1:  EE criterion = 1.046e-23  

Treatment-effects estimation                    Number of obs     =      9,913
Estimator      : regression adjustment
Outcome model  : linear
Treatment model: none
------------------------------------------------------------------------------
             |               Robust
      assets | Coefficient  std. err.      z    P>|z|     [95% conf. interval]
-------------+----------------------------------------------------------------
ATE          |
       e401k |
  (Eligible  |
         vs  |
Not elig..)  |   7929.242   1216.273     6.52   0.000      5545.39    10313.09
-------------+----------------------------------------------------------------
POmean       |
       e401k |
Not eligi..  |   14094.12   863.7641    16.32   0.000     12401.18    15787.07
------------------------------------------------------------------------------



Contrasts of predictive margins                          Number of obs = 9,913
Model VCE: OLS

Expression: Linear prediction, predict()
1._at: e401k = 0
2._at: e401k = 1

------------------------------------------------
             |         df           F        P>F
-------------+----------------------------------
         _at |          1       34.39     0.0000
             |
 Denominator |       9889
------------------------------------------------

--------------------------------------------------------------
             |            Delta-method
             |   Contrast   std. err.     [95% conf. interval]
-------------+------------------------------------------------
         _at |
   (2 vs 1)  |   7929.242   1352.153      5278.746    10579.74
--------------------------------------------------------------

40.1.1 DoubleML

The R package DoubleML implements the double/debiased machine learning framework of Chernozhukov et al. (2018). It provides functionalities to estimate parameters in causal models based on machine learning methods. The double machine learning framework consists of three key ingredients: Neyman orthogonality, High-quality machine learning estimation and Sample splitting.

They consider a partially linear model:

\[ y_i = \theta d_i + g_0(x_i) + \eta_i \tag{40.1}\]

\[ d_i = m_0(x_i) + v_i \tag{40.2}\]

This model is quite general, except it does not allow interaction of \(d\) and \(x\); therefore no heterogeneous treatment effect across \(x\). But “DoubleML” implements more than partially linear model, it actually allows for heterogeneous treatment effects, in models such as interactive regression model.

The basic idea of doubleML is to use any machine learning algorithm to estimate outcome equation (\(l_0(X) = E(Y | X)\)) and treatment equation (\(m_0(X) = E(D | X)\)). Then get the residuals, namely \(\hat W=Y-\hat l_0(X)\) and \(\hat V = D - \hat m_0(X)\).

Then regress \(\hat W\) on \(\hat V\). Based on FWL theorem, you get \(\hat \theta\).

An important component here is to specify a Neyman-orthogonal score function. In the case of PLR, it can be the product of the two residuals:

\[\psi (W; \theta, \eta) = (Y-D\theta -g(X))(D-m(X)) \tag{40.3}\]

The estimators \(\hat \theta\) is to solve the equation that the sample mean of this score function being 0.

The variance of the estimator comes from this score, scaled. Under suitable regularity conditions, \(\text{Var}(\hat\theta) \approx E[\psi^2] / (n J^2)\), where \(J = E[\partial \psi / \partial \theta] = -E[(D - m(X))^2]\) is the derivative of the score in \(\theta\) and \(n\) the sample size. Cross-fitting makes this valid with flexible learners, provided the nuisance estimates converge fast enough and overlap holds.

Now we try to replicate the CATE estimation in Stata using the R package DoubleML. I have not found a way to include factor variables in the lasso regression in R, so I included them as numeric variables.

The example in stata’s cate command is to use lasso on both outcome and treatment regression, then random forest on the individual treatment effect to get ATE. Here I try to replicate it in R.

Code
library(haven)
library(DoubleML)
library(mlr3)
library(mlr3learners)
library(data.table)
library(dplyr)
# get rid of labels because doubleML does not like them
data <- read_dta("https://www.stata-press.com/data/r19/assets3.dta") |>
  zap_labels()


  # pension, married, twoearn, ira, ownhome are already binary 0/1, so
  # passing them as numeric is fine. incomecat, however, has 5 unordered
  # categories (0-4) -- passing it as a single numeric column would force
  # the ML learners (especially the linear regr.glmnet below) to treat
  # category 2 as twice category 1, which is not a meaningful assumption
  # for a nominal variable. One-hot encode it into dummy columns instead.
incomecat_dummies <- model.matrix(~ as.factor(incomecat) - 1, data = data)
colnames(incomecat_dummies) <- paste0("incomecat_", 0:(ncol(incomecat_dummies) - 1))
data <- cbind(data, incomecat_dummies)

assets3 <- data.table::setDT(data)
dml_data = DoubleMLData$new(data = assets3,
                             y_col = "assets",
                             d_cols = "e401k",
                             x_cols = c("age","educ", colnames(incomecat_dummies),"pension", "married","twoearn","ira","ownhome"))

print(dml_data)
================= DoubleMLData Object ==================


------------------ Data summary      ------------------
Outcome variable: assets
Treatment variable(s): e401k
Covariates: age, educ, incomecat_0, incomecat_1, incomecat_2, incomecat_3, incomecat_4, pension, married, twoearn, ira, ownhome
Instrument(s): 
Selection variable: 
No. Observations: 9913
Code
lgr::get_logger("mlr3")$set_threshold("warn")
learner = lrn("regr.glmnet", lambda=1)
ml_g_sim = learner$clone()
ml_m_sim = learner$clone()
set.seed(123)
obj_dml_plr = DoubleMLPLR$new(dml_data, ml_l=ml_g_sim, ml_m=ml_m_sim, n_folds=10)
obj_dml_plr$fit()
obj_dml_plr$summary()
Estimates and significance testing of the effect of target variables
      Estimate. Std. Error t value Pr(>|t|)    
e401k      7553       1281   5.897 3.69e-09 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

DoubleML with lasso learners gives an ATE of $7,553 with a standard error of $1,281.

If we use random forest on the two models:

Code
# suppress messages from mlr3 package during fitting
lgr::get_logger("mlr3")$set_threshold("warn")
learner = lrn("regr.ranger", num.trees=2000,  max.depth=5, min.node.size=2,
              num.threads = 1)  # single thread so set.seed() fixes the forest
ml_l = learner$clone()
ml_m = learner$clone()
# learner = lrn("regr.glmnet")
# ml_g_sim = learner$clone()
# ml_m_sim = learner$clone()
set.seed(123)
obj_dml_plr = DoubleMLPLR$new(dml_data, ml_l=ml_l, ml_m=ml_m, n_folds=5)
obj_dml_plr$fit()
obj_dml_plr$summary()
Estimates and significance testing of the effect of target variables
      Estimate. Std. Error t value Pr(>|t|)    
e401k      9114       1375   6.627 3.43e-11 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

We can do the same in Stata:

Code
clear all
webuse assets3
global catecovars age educ i.(incomecat pension married twoearn ira ownhome)
cate po (assets $catecovars) (e401k),  omethod(rforest) tmethod(rforest) nolog  xfolds(5)
(Excerpt from Chernozhukov and Hansen (2004))



Conditional average treatment effects     Number of observations       = 9,913
Estimator:       Partialing out           Number of folds in cross-fit =     5
Outcome model:   Random forest            Number of outcome controls   =    17
Treatment model: Random forest            Number of treatment controls =    17
CATE model:      Random forest            Number of CATE variables     =    17

------------------------------------------------------------------------------
             |               Robust
      assets | Coefficient  std. err.      z    P>|z|     [95% conf. interval]
-------------+----------------------------------------------------------------
ATE          |
       e401k |
  (Eligible  |
         vs  |
Not elig..)  |   8282.334   1181.772     7.01   0.000     5966.103    10598.57
-------------+----------------------------------------------------------------
POmean       |
       e401k |
Not eligi..  |   14002.82   855.4206    16.37   0.000     12326.23    15679.42
------------------------------------------------------------------------------

With random forests DoubleML gives $9,114 (SE $1,375), while Stata’s cate with rforest for both models gives $8,282 (SE $1,182). The gap, about $830, is smaller than either standard error. The two packages tune and cross-fit their forests differently, so the numbers need not match exactly.

40.2 AIPW

Stata’s cate also has “aipw” option.

Code
clear all
webuse assets3
global catecovars age educ i.(incomecat pension married twoearn ira ownhome)
cate aipw (assets $catecovars) (e401k),  nolog
(Excerpt from Chernozhukov and Hansen (2004))



Conditional average treatment effects     Number of observations       = 9,913
Estimator:       Augmented IPW            Number of folds in cross-fit =    10
Outcome model:   Linear lasso             Number of outcome controls   =    17
Treatment model: Logit lasso              Number of treatment controls =    17
CATE model:      Random forest            Number of CATE variables     =    17

------------------------------------------------------------------------------
             |               Robust
      assets | Coefficient  std. err.      z    P>|z|     [95% conf. interval]
-------------+----------------------------------------------------------------
ATE          |
       e401k |
  (Eligible  |
         vs  |
Not elig..)  |   8185.616   1162.852     7.04   0.000     5906.468    10464.76
-------------+----------------------------------------------------------------
POmean       |
       e401k |
Not eligi..  |   13943.48    836.799    16.66   0.000     12303.39    15583.58
------------------------------------------------------------------------------

Stata’s AIPW gives an ATE of $8,186 with a standard error of $1,163, on 9,913 households.

I’ll try to do this with “npcausal”:

Code
library(npcausal)
#SL.library <- c("SL.earth","SL.gam","SL.glmnet","SL.glm.interaction", "SL.mean","SL.ranger", "SL.xgboost")
#SL.library <- c("SL.glmnet")
SL.lasso = function(...) {
  SL.glmnet(..., alpha=1)
}
SL.library <- c("SL.lasso")

Y <- data$assets
A <- data$e401k
# incomecat is nominal (5 categories); use the one-hot dummies created above
# rather than the raw numeric column, for the same reason as in the
# DoubleML example.
# Two coercions, both for npcausal/SuperLearner:
#   * as.data.frame(): `data` became a data.table in the DoubleML chunk
#     (setDT() works by reference), and data.table evaluates a character
#     vector in j instead of selecting columns.
#   * as.numeric on every column: read_dta() returns haven_labelled columns,
#     which SuperLearner rejects.
W <- as.data.frame(data)[, c("age", "educ", grep("^incomecat_", names(data), value = TRUE), "pension", "married", "twoearn", "ira", "ownhome")]
W <- as.data.frame(lapply(W, as.numeric))
# Wrapped so a failure inside npcausal is reported rather than stopping the render.
aipw <- tryCatch(
  ate(y = Y, a = A, x = W, nsplits = 10, sl.lib = SL.library),
  error = function(e) {
    message("npcausal::ate() failed: ", conditionMessage(e))
    NULL
  }
)

  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |==                                                                    |   2%
  |                                                                            
  |====                                                                  |   5%
  |                                                                            
  |=====                                                                 |   8%
  |                                                                            
  |=======                                                               |  10%
  |                                                                            
  |=========                                                             |  12%
  |                                                                            
  |==========                                                            |  15%
  |                                                                            
  |============                                                          |  18%
  |                                                                            
  |==============                                                        |  20%
  |                                                                            
  |================                                                      |  22%
  |                                                                            
  |==================                                                    |  25%
  |                                                                            
  |===================                                                   |  28%
  |                                                                            
  |=====================                                                 |  30%
  |                                                                            
  |=======================                                               |  32%
  |                                                                            
  |========================                                              |  35%
  |                                                                            
  |==========================                                            |  38%
  |                                                                            
  |============================                                          |  40%
  |                                                                            
  |==============================                                        |  42%
  |                                                                            
  |================================                                      |  45%
  |                                                                            
  |=================================                                     |  48%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |=====================================                                 |  52%
  |                                                                            
  |======================================                                |  55%
  |                                                                            
  |========================================                              |  58%
  |                                                                            
  |==========================================                            |  60%
  |                                                                            
  |============================================                          |  62%
  |                                                                            
  |==============================================                        |  65%
  |                                                                            
  |===============================================                       |  68%
  |                                                                            
  |=================================================                     |  70%
  |                                                                            
  |===================================================                   |  72%
  |                                                                            
  |====================================================                  |  75%
  |                                                                            
  |======================================================                |  78%
  |                                                                            
  |========================================================              |  80%
  |                                                                            
  |==========================================================            |  82%
  |                                                                            
  |============================================================          |  85%
  |                                                                            
  |=============================================================         |  88%
  |                                                                            
  |===============================================================       |  90%
  |                                                                            
  |=================================================================     |  92%
  |                                                                            
  |==================================================================    |  95%
  |                                                                            
  |====================================================================  |  98%
  |                                                                            
  |======================================================================| 100%
     parameter       est        se    ci.ll    ci.ul pval
1      E{Y(0)} 13968.168  828.5825 12344.15 15592.19    0
2      E{Y(1)} 22032.806  890.5290 20287.37 23778.24    0
3 E{Y(1)-Y(0)}  8064.638 1157.6473  5795.65 10333.63    0
Code
if (!is.null(aipw)) aipw$res
     parameter       est        se    ci.ll    ci.ul pval
1      E{Y(0)} 13968.168  828.5825 12344.15 15592.19    0
2      E{Y(1)} 22032.806  890.5290 20287.37 23778.24    0
3 E{Y(1)-Y(0)}  8064.638 1157.6473  5795.65 10333.63    0

Note here to match the Stata results, I included only lasso (glmnet) in the SuperLearner library. npcausal gives an ATE of $8,065 with a standard error of $1,158, against $8,186 from Stata’s AIPW.

Or we can use a similar package with more functionalities: “AIPW”.

Code
library(AIPW)
library(SuperLearner)

#SuperLearner libraries for outcome (Q) and exposure models (g)
#sl.lib <- c("SL.glmnet")

AIPW_sl <- AIPW$new(Y= Y,
                     A= A,
                     W= W,
                     Q.SL.library = SL.library,
                     g.SL.library = SL.library,
                     k_split = 10,
                     verbose=FALSE)

AIPW_sl$fit()
AIPW_sl$summary()
AIPW_sl$result
                  Estimate        SE   95% LCL  95% UCL    N
Mean of Exposure 22148.599  880.3483 20423.117 23874.08 3682
Mean of Control  13907.211  826.3618 12287.541 15526.88 6231
Mean Difference   8241.389 1149.5322  5988.306 10494.47 9913
Code
# library(ggplot2)
# AIPW_sl$plot.p_score()
# AIPW_sl$plot.ip_weights()

AIPW gives $8,241 with a standard error of $1,150, close to npcausal and to Stata’s AIPW.

40.3 Summary

Stata 19’s cate command estimates conditional average treatment effects with partialling out, which is double machine learning, or with AIPW. It uses lasso or random forests for the nuisance models. A fully interacted regression gives similar numbers, but it is regression adjustment, a different idea. DoubleML, npcausal and AIPW in R implement the same estimators.

In the 401(k) data, the group ATEs rise from about $4,000 in the lowest income category to $20,350 in the highest. A single ATE would hide that spread. Overall ATEs depend on the learners and the software: $7,553 from DoubleML with lasso, $9,114 with random forests in R against $8,282 in Stata, and AIPW gives $8,186 in Stata, $8,065 from npcausal and $8,241 from AIPW. The estimates span $7,553 to $9,114 with standard errors between $1,150 and $1,375, so the choice of learner and software moves the ATE by up to about one standard error.


Systematic treatment: R · Julia.