Method 01 · R
Heterogeneous treatment effects
- Question
- In a randomised trial, is the effect the same for everyone, and if not, who gains and who loses?
- Input
- Outcome, treatment, covariates, and the assignment probabilities. Clustered and stratified designs are handled.
- Output
- Three summaries, each with a standard error and a p-value: how much heterogeneity there is (BLP), the effect in each quartile of predicted benefit (GATES), and which covariates describe the most- and least-affected groups (CLAN).
- Use it when
- The effect of an experiment may vary across people, and the finding has to hold up when a referee asks what another random split would have shown.
Randomised trials are usually summarised by one number, the average effect. Averages hide structure: a program can help some participants, leave most unchanged and harm others, and whether it should be scaled, targeted or redesigned depends on that structure. The difficulty is that individual effects have to be estimated with flexible methods, and a hypothesis suggested by a fitted model cannot be tested on the data that produced it.
Chernozhukov, Demirer, Duflo and Fernández-Val resolve this by changing the
target of inference. Instead of the individual effect function, they test three summaries
of it, each estimated on data the learner never saw: the best linear predictor of the
effect (BLP), the average effect by group of predicted benefit (GATES), and the covariate
profile of the most and least affected (CLAN). A single sample split is
arbitrary, and the answer moves with the seed, so the procedure is repeated over many
splits and the medians are reported, with p-values doubled to pay for taking the median.
This is valid and deliberately conservative. Fava (2025) proves a central limit theorem
for split-sample averages, which gives an exact and less conservative way to pool the
splits; his ensembleHTE package implements it.
This page implements the median-pooled procedure step by step in plain R and runs it on a simulated trial in which every individual effect is known, so each estimate appears next to the value it is estimating. Two parts go beyond a demonstration. Section 2 shows how far the answer moves across splits, which is the problem the pooling exists to solve, and Section 6 reruns the entire procedure on 150 trials with no heterogeneity at all, to measure how often the pooled test rejects a true null. The implementation is a simplified version of a pipeline I built and use as a research assistant in the analysis of a randomised controlled trial; the run box lists the simplifications.
The rest of the page is organised as follows. Section 1 states what is estimated and where this implementation differs from the original procedure. Sections 2 and 3 present the splitting problem and the estimation pipeline. Sections 4 and 5 describe the simulated trial and the results, Section 6 the size and power of the pooled tests, and Section 7 whether the ensemble of learners earns its place.
01The method
The three estimands answer the questions applied work asks. The BLP regression measures whether the predicted effects line up with the true ones at all: its second coefficient is zero when the prediction is pure noise and grows with genuine heterogeneity. GATES sorts people into quartiles of predicted benefit and estimates the effect in each, which gives the shape of the heterogeneity. CLAN describes who sits in the extreme quartiles. All three are estimated on held-out data only.
Table 1 lists what this implementation keeps from Chernozhukov et al. and where it differs. The differences are in the plumbing rather than the estimands: cross-fitting instead of one auxiliary and one main sample, so that every observation is held out once per repetition, and a tournament that chooses the learner inside each fold instead of a single learner chosen in advance.
| Chernozhukov et al. | This implementation | |
|---|---|---|
| Estimands | BLP, GATES, CLAN | the same, unchanged |
| Splitting | auxiliary / main, repeated S times | M × K cross-fitting; every observation is held out once per repetition |
| Proxy | one ML method, chosen by the analyst | six candidates, ranked by R-loss inside each fold's training data |
| Point estimate | median over splits | median over all 180 fold-level estimates |
| Standard error | split-specific bounds, median-aggregated | √median(se² + (est − median)²) |
| p-value | 2 × median of split p-values | min(1, 2 × min(median p⁺, median p⁻)) |
| Justification | conservative by construction | the same; Section 6 measures the conservatism |
The published Chernozhukov et al. estimator is implemented in GenericML; the averaged many-splits estimator of Fava (2025) in ensembleHTE. The script here spells the steps out in plain R instead of calling either, so that each one can be read and changed.
02Why one split is not enough
The demo runs the whole procedure 60 times on the same data, changing only the random split. Each run is what a single analysis would have reported. The heterogeneity coefficient ranges from 1.45 to 2.69 across those runs. Every run finds the heterogeneity, but the estimate it reports ranges from 1.45 to 2.69, a spread the reported standard error has to own.
03The procedure
Everything that produces a fold's effect proxy happens inside that fold's training data: fitting the candidates, ranking them, picking the winners, refitting. The held-out fold is used only for prediction and for the final regression. That is what makes the fold-level regression a genuine out-of-sample test.
Ranking six different learners on the same scale requires writing the effect function as a weighted least-squares problem. With m(x) = E[Y|X] and the known assignment probability e(x), the R-learner identity Y − m(x) = (D − e(x)) τ(x) + error turns any regression learner into a candidate estimator of τ, and gives all of them a common loss (Nie & Wager, 2021).
Rcode/ensemble_hte_demo.Rthe loss that ranks the candidates
# R-loss on data the candidate never saw:
# sum_i w_i [ (Y_i - m(x_i)) - (D_i - e(x_i)) * tau_a(x_i) ]^2
r_loss <- function(Y, m_hat, D, e, tau_hat, w) {
sum(w * ((Y - m_hat) - (D - e) * tau_hat)^2)
}
# ---------------------------------------------------------------------
# 4. One repetition: confined tournament, then proxy for every fold
# ---------------------------------------------------------------------
# The confinement is the point. Everything that produces fold k's proxy --
# candidate fitting, scoring, winner selection, winner refit -- happens
# strictly inside fold k's training complement. Fold k's rows touch the
# model only when they are predicted. This is what licenses treating the
# fold-level regression as an honest out-of-sample test.
#
# complement (K-1 folds) held-out fold k
# |------- fit part -------|-- score --| |---- predict ----|
# fit 6 candidates rank by proxy = mean of
# R-loss refit winners
# winners refit on the WHOLE complement ->
Rcode/ensemble_hte_demo.Rone fold, start to finish
# --- (a) nuisance + R-learner pieces on the fit part ---------------
m_fit <- fit_nuisance(dat$Y, dat$X, fit_idx)
m_hat <- m_fit(dat$X)
dev <- dat$D - dat$prop_score
z <- (dat$Y - m_hat) / ifelse(abs(dev) < 1e-6, sign(dev) * 1e-6, dev)
w <- dev^2
# --- (b) fit every candidate, score on the held-out score part -----
sc <- vapply(CANDIDATES, function(a) {
th <- try(fit_tau(a, z, w, dat$X, fit_idx, dat$X[score_idx, , drop = FALSE]),
silent = TRUE)
if (inherits(th, "try-error") || var(th) < .Machine$double.eps) return(NA_real_)
r_loss(dat$Y[score_idx], m_hat[score_idx], dat$D[score_idx],
dat$prop_score[score_idx], th, w[score_idx])
}, numeric(1))
valid <- names(sc)[is.finite(sc)]
winners <- valid[order(sc[valid])][seq_len(min(cfg$tournament_k, length(valid)))]
tour[[k]] <- data.frame(rep = m, fold = k, algorithm = names(sc),
rloss = as.numeric(sc),
selected = names(sc) %in% winners)
# --- (c) refit on the FULL complement, predict fold k --------------
# In production only the winners are refitted. Here every candidate
# is refitted as well, so that section 3 can show what each learner
# would have produced on its own. The proxy is still the equal-weight
# average of the winners.
m_full <- fit_nuisance(dat$Y, dat$X, comp_idx)
mh <- m_full(dat$X)
z2 <- (dat$Y - mh) / ifelse(abs(dev) < 1e-6, sign(dev) * 1e-6, dev)
for (a in CANDIDATES) {
th <- try(fit_tau(a, z2, w, dat$X, comp_idx, dat$X[test_idx, , drop = FALSE]),
silent = TRUE)
if (inherits(th, "try-error")) next
ite_algo[test_idx, a] <- th
ho <- ho + 1L
holdout[[ho]] <- data.frame(
rep = m, fold = k, algorithm = a,
rloss = r_loss(dat$Y[test_idx], mh[test_idx], dat$D[test_idx],
dat$prop_score[test_idx], th, w[test_idx]) / length(test_idx))
}
ite[test_idx] <- rowMeans(ite_algo[test_idx, winners, drop = FALSE], na.rm = TRUE)
ho <- ho + 1L
holdout[[ho]] <- data.frame(
rep = m, fold = k, algorithm = "ensemble",
rloss = r_loss(dat$Y[test_idx], mh[test_idx], dat$D[test_idx],
dat$prop_score[test_idx], ite[test_idx], w[test_idx]) /
length(test_idx))
}
Inference is one weighted regression per repetition and fold, on that fold's rows only, with Horvitz–Thompson weights 1/[p(1−p)] and standard errors clustered at the household. The proxy is demeaned and cut into quartiles within the fold; a full-sample mean or full-sample quantiles would let the other folds back in.
Rcode/ensemble_hte_demo.Rthe best linear predictor, one fold at a time
HT_w <- function(p) 1 / (p * (1 - p))
blp_fold <- function(d, idx, ite) {
W1 <- d$D[idx] - d$prop_score[idx]
S <- ite[idx] - mean(ite[idx])
W2 <- W1 * S
f <- lm(y ~ W1 + W2, data = data.frame(y = d$Y[idx], W1 = W1, W2 = W2),
weights = HT_w(d$prop_score[idx]))
V <- vcovCL(f, cluster = d$cluster_id[idx])
b <- coef(f)
# What each coefficient is estimating in this fold, computed from the
# true tau the simulation knows: beta1 targets the mean effect, and
# beta2 targets the slope of the true effect on the demeaned proxy --
# which exceeds 1 when the proxy is a compressed version of the truth.
data.frame(term = c("beta1_ate", "beta2_het"),
estimate = c(b[["W1"]], b[["W2"]]),
se = c(sqrt(V["W1", "W1"]), sqrt(V["W2", "W2"])),
target = c(mean(d$tau[idx]), cov(d$tau[idx], S) / var(S)))
}
Rcode/ensemble_hte_demo.Rpooling across splits
pool_splits <- function(est, se) {
ok <- is.finite(est) & is.finite(se) & se > 0
est <- est[ok]; se <- se[ok]
med <- median(est)
se_infl <- sqrt(median(se^2 + (est - med)^2))
t_s <- est / se
p_med <- min(1, 2 * min(median(1 - pnorm(t_s)), median(pnorm(t_s))))
data.frame(est = med, se = se_infl, p = p_med,
p_wald = 2 * pnorm(-abs(med / se_infl)),
se_naive = mean(se), n_splits = length(est))
}
04The simulated trial
3,000 people in 600 households, randomised by household within 8 strata, so the assignment probability varies by stratum and is known by design rather than estimated. Ten covariates, of which three move the effect. The true effect is
τ(x) = 0.45·x1 + 0.90·1{x1>0.5}·1{x2>0} − 0.55·1{x4<−0.5} + 0.02
part linear, part an interaction between two thresholds, part a threshold with the opposite sign, so that no single learner family is right for all of it. The average effect is -0.019 and 58 percent of people are genuinely harmed. A trial report that stops at the average calls this a null result.
05Results
β1 is the average effect. β2 is the coefficient on the demeaned proxy: zero when the proxy is noise, one when the proxy equals the true effect. When the proxy is a compressed version of the truth, which is the usual case, the slope of the true effect on the proxy exceeds one, so a β2 above one is expected. Because the simulation knows every true effect, the value each coefficient is estimating can be computed exactly; Table 2 reports it in the target column.
| term | estimate | SE | SE if splits ignored | p | target |
|---|---|---|---|---|---|
| β1 (average effect) | 0.009 | 0.116 | 0.099 | 0.9319 | -0.020 |
| β2 (heterogeneity loading) | 1.938*** | 0.578 | 0.487 | <0.0001 | 1.914 |
Notes: Medians over 180 fold-level estimates, with the standard error inflated by the across-split spread and the doubled median p-value. “SE if splits ignored” averages the fold-level standard errors instead. The target column is computed from the true effects of the simulation: the mean effect for β1, and the slope of the true effect on the demeaned proxy for β2, aggregated across folds by median.
The average effect is recovered as a null (0.009 against a true -0.019, p = 0.93), and the heterogeneity is found: 1.94 against a target of 1.91, within one standard error of its target, with p < 0.0001. Sorting people into quartiles of the proxy and estimating the effect separately in each gives the shape.
estimate, 95% interval true effect in that group pooled average effect
CLAN compares covariate means between the most- and the least-affected quartile. x1, x2 and x4 are the three covariates the true effect depends on; x7 and x9 play no part in it and are included as placebos.
| covariate | G1 mean | G4 mean | difference | SE | p |
|---|---|---|---|---|---|
| x1 | -1.03 | 1.09 | 2.117*** | 0.105 | <0.0001 |
| x2 | -0.18 | 0.27 | 0.428*** | 0.135 | <0.0001 |
| x4 | -0.56 | 0.35 | 0.917*** | 0.133 | <0.0001 |
| x7 placebo | -0.12 | 0.07 | 0.195** | 0.110 | 0.0346 |
| x9 placebo | -0.02 | 0.00 | 0.029 | 0.110 | 0.7453 |
The three drivers separate sharply. Of the two placebos, x9 shows nothing (p = 0.75), while x7 crosses the 5 percent threshold (p = 0.0346). The CLAN p-values are computed covariate by covariate, with no adjustment for the number of comparisons, so among several placebos an occasional p-value below 0.05 is to be expected; in applied work, the covariates to examine should be specified before estimation.
06Does the test reject at the right rate?
A simulated trial in which the heterogeneity is found shows that the procedure can detect an effect that is there. It does not show that the p-values mean what they claim. That requires the opposite experiment: simulate many trials in which the treatment effect is the same constant for everyone, run the entire procedure, from the tournament to the pooling, on each of them, and count how often the tests reject. A test with a nominal size of 5 percent may reject in at most about 5 percent of such trials; because the doubled median p-value is conservative by construction, the rejection rate should come out below that. Table 4 counts the rejections, and repeats the exercise on trials with the heterogeneous effect of Section 4 to measure power.
| test | no heterogeneity, nominal 5% | no heterogeneity, nominal 10% | with heterogeneity, nominal 5% |
|---|---|---|---|
| BLP heterogeneity (β2) | 0 of 150 (0.0%) | 1 of 150 (0.7%) | 100 of 100 (100.0%) |
| GATES, top minus bottom quartile | 0 of 150 (0.0%) | 1 of 150 (0.7%) | 100 of 100 (100.0%) |
| β2 from a single repetition | 1 of 150 (0.7%) | 98 of 100 (98.0%) |
Notes: 150 trials without and 100 trials with heterogeneity, each independently simulated and analysed with the full procedure. To keep the runtime at about half an hour, these trials are smaller than the one on this page: 1,600 people in 400 households and M = 10 repetitions of K = 2 folds, with the learners, the tournament and the pooling unchanged. The last row is the test a single repetition of the procedure would have delivered.
Under the null, the pooled β2 test rejects in 0 of 150 (0.0%) trials at a nominal 5 percent and the GATES comparison in 0 of 150 (0.0%): below the nominal level, which is the conservatism the doubled median p-value was expected to show. The median pooled estimate is -0.07 under the null and 1.83 with heterogeneity, where the same tests reject in 100 of 100 (100.0%) and 100 of 100 (100.0%) of the trials. A conservative test gives up power somewhere; at this effect size, none of that is visible, and pooling over splits even beats the single repetition, which misses the effect in 2 of 100 (2.0%) trials.
Rcode/mc_size_check.Rone trial of the size check
# One complete run of the procedure on one freshly simulated trial:
# tournament, fold-level BLP and GATES, median pooling. Returns the
# pooled p-values and, for comparison, the p-value a single repetition
# (one K-fold pass) would have reported.
run_once <- function(seed, tau_scale) {
cfg1 <- cfg_mc
cfg1$seed <- seed
cfg1$tau_scale <- tau_scale
dat <- simulate_trial(cfg1)
reps <- lapply(seq_len(cfg1$M), function(m) process_repetition(m, dat, cfg1))
blp_rows <- list(); tb_rows <- list(); r <- 0L
for (m in seq_along(reps)) {
rp <- reps[[m]]
for (k in seq_len(cfg1$K)) {
idx <- which(rp$folds == k)
r <- r + 1L
blp_rows[[r]] <- cbind(rep = m, blp_fold(dat, idx, rp$ite))
g <- gates_fold(dat, idx, rp$ite, cfg1$n_groups)
if (!is.null(g)) tb_rows[[length(tb_rows) + 1L]] <- g$top_bottom
}
}
blp <- do.call(rbind, blp_rows)
b2 <- blp[blp$term == "beta2_het", ]
tbd <- do.call(rbind, tb_rows)
one <- b2[b2$rep == 1L, ]
c(p_beta2 = pool_splits(b2$estimate, b2$se)$p,
p_gap = pool_splits(tbd$estimate, tbd$se)$p,
p_single = pool_splits(one$estimate, one$se)$p,
est_beta2 = pool_splits(b2$estimate, b2$se)$est)
}
07Does the ensemble earn its place?
The demo refits every candidate on each fold, not only the winners, so each learner's own cross-fitted proxy can be compared with the ensemble's. The comparison is on held-out R-loss, the quantity the tournament minimises, with the rank correlation and the RMSE against the true effect alongside.
| learner | held-out R-loss | rank corr. with truth | RMSE vs truth | selection rate |
|---|---|---|---|---|
| ranger | 0.1852 | 0.896 | 0.418 | 0.79 |
| ensemble of the winners | 0.1852 | 0.941 | 0.421 | |
| xgboost | 0.1856 | 0.857 | 0.414 | 0.52 |
| lm | 0.1858 | 0.911 | 0.446 | 0.83 |
| glmnet | 0.1868 | 0.923 | 0.460 | 0.42 |
| grf | 0.1870 | 0.949 | 0.450 | 0.31 |
| rpart | 0.1899 | 0.894 | 0.397 | 0.13 |
No single learner is best at everything. ranger has the lowest R-loss but comes fifth of 7 on rank correlation (0.896); grf ranks people best (0.949) but comes sixth on R-loss. The ensemble comes second on R-loss, within 0.00003 of the best, second on rank correlation and fourth on RMSE. It wins nothing outright. What it delivers is a position near the top on every metric without the winning learner having to be known in advance, which is the case for running a tournament rather than picking a favourite.
The selection rates show that the tournament does not settle on one answer: they are spread across the pool and change from fold to fold.
References
- Chernozhukov, V., Demirer, M., Duflo, E. & Fernández-Val, I. Generic Machine Learning Inference on Heterogeneous Treatment Effects in Randomized Experiments. arXiv:1712.04802; NBER Working Paper 24678.The estimands on this page (BLP, GATES and CLAN) and the median aggregation over splits with doubled p-values that this script uses.
- Fava, B. (2025). Training and Testing with Multiple Splits: A Central Limit Theorem for Split-Sample Estimators. arXiv:2511.04957.A central limit theorem for split-sample averages: the exact and less conservative alternative to the median pooling used here.
- Nie, X. & Wager, S. (2021). Quasi-oracle estimation of heterogeneous treatment effects. Biometrika 108(2), 299–319.The R-learner loss that lets six different learners be ranked on one scale.
GenericML(R package)Reference implementation of the Chernozhukov et al. estimator.ensembleHTE(R package)Implements the averaged many-splits estimator of Fava (2025). The implementation to use in production work.
Run it
Rscript code/ensemble_hte_demo.R Rscript code/mc_size_check.R
The demo takes 655 s
on 4 cores at M = 60 and n = 3,000; a
lower M gives a faster pass. The size check takes about half
an hour on 8 cores. In the research pipeline this demo is based on, twelve tuned
candidates compete rather than six, the baseline nuisance is refitted per candidate
rather than shared, and only the winners are refitted; this script refits every candidate
so that Section 7 can exist. All numbers on this page are read from the results
files the two scripts write.