*! version 30aug2024

Cluster sampling with cross-fit folds - Basic example with pystacked

Load the data, define global macros and set the seed.

. webuse nlsw88, clear

. gen lwage = ln(wage)

. global Y lwage

. global D union

. global X age-c_city hours-tenure

. set seed 42

Initialize the model.
The fcluster(industry) ("fold-cluster") option tells ddml
to ensure that clusters (here, identified by the variable industry)
are not split across cross-fit folds, i.e., each cluster appears in only one cross-fit fold.
Here we specify 2 cross-fit folds,
so all observations for each cluster will appear in either fold 1 or in fold 2.
NB: This example is somewhat artificial, because there are only 12 clusters (industries).

. ddml init partial, kfolds(2) fcluster(industry)

. tab industry m0_fid_1

Since there are 12 clusters defined by industry,
we could achieve the same cross-fit split either by specifying fcluster(industry),
or by using fcluster(industry) as the fold identifier and specifying foldvar(industry).
(NB: The split is the same but the fold numbering is different.)

. ddml init partial, foldvar(industry)

. tab industry m0_fid_1

. ddml init partial, kfolds(12) fcluster(industry)

. tab industry m0_fid_1

Estimation is standard,
but to obtain cluster-robust SEs the covariance estimator
needs to be requested with ddml estimate:

. ddml E[Y|X]: pystacked $Y $X

. ddml E[D|X]: pystacked $D $X

. ddml crossfit

. ddml estimate, cluster(industry)