Risk-based and effect-based heterogeneous treatment effects (HTE) with the grf R package

Author

Kuan Liu

1. Hands-on exercise: risk-based and effect-based HTE analysis of an RCT

This tutorial walks through the two predictive approaches to HTE from the lecture on one RCT data set:

  1. a risk-based analysis, where patients are grouped by their predicted baseline risk from a treatment-blind prognostic model

  2. an effect-based analysis, where a causal forest (grf R package) predicts the treatment effect of each patient.

1.1 Data

  • Indomethacin for the Prevention of Post-ERCP Pancreatitis Dataset Description Document

  • This data set is provided by B. Joseph Elmunzer, the primary author of a study published on 2012 in the New England Journal of Medicine, volume 366, pages 1414-1422.

  • R package medicaldata

  • This RCT data contains baseline characteristics and outcomes for 602 participants at increased risk of post-ERCP pancreatitis at 4 centers.

  • Variable code book

  • We will be using a modified version of this data: all variables are numeric, binary variables are coded 0/1.

    • outcome: post-ERCP pancreatitis (1 = yes, 0 = no). This is a bad outcome, so a treatment effect below 0 (fewer events) means benefit.
    • rx: treatment (1 = indomethacin, 0 = placebo).
    • baseline covariates: age, risk (risk score), gender, and binary clinical and procedural risk factors.
library(mice)    # multiple imputation (loaded first: it also has filter() and complete() functions)
library(grf)     # causal forest
library(tidyverse)
library(gtsummary)
library(DT)

options(scipen = 999)

indo <- read.csv("indo.csv", header = TRUE, fileEncoding = "UTF-8-BOM")

# look at new data;
datatable(indo, rownames = FALSE)
str(indo)
'data.frame':   601 obs. of  19 variables:
 $ id     : int  1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 ...
 $ rx     : int  1 0 0 0 1 0 1 1 1 1 ...
 $ outcome: int  1 0 0 1 0 0 0 0 0 0 ...
 $ age    : int  26 24 57 29 38 59 60 29 53 20 ...
 $ risk   : num  2 1 1 2 3.5 3 1.5 1 2 2 ...
 $ gender : int  1 2 1 1 1 1 1 2 2 2 ...
 $ sod    : int  1 0 1 1 1 1 0 0 0 0 ...
 $ pep    : int  0 1 0 0 1 0 0 0 0 0 ...
 $ recpanc: int  1 0 0 0 0 0 1 0 1 0 ...
 $ psphinc: int  0 0 0 0 1 0 0 0 0 0 ...
 $ precut : int  0 0 0 0 0 1 0 0 0 1 ...
 $ difcan : int  0 0 0 0 0 1 0 1 0 1 ...
 $ paninj : int  0 0 0 0 0 0 1 0 1 0 ...
 $ asa    : int  0 0 0 0 0 1 0 0 0 0 ...
 $ sodsom : int  0 0 0 0 1 0 0 0 0 0 ...
 $ bsphinc: int  0 1 0 1 1 1 0 1 0 1 ...
 $ bstent : int  0 1 0 0 0 0 0 0 0 1 ...
 $ chole  : int  0 1 0 1 0 0 0 1 0 1 ...
 $ train  : int  1 0 0 1 1 0 1 1 1 0 ...
# baseline covariates (candidate effect modifiers), selected by name;
covariates <- c("age", "risk", "gender", "sod", "pep", "recpanc", "psphinc", "precut","difcan", "paninj", "asa", "sodsom", "bsphinc", "bstent", "chole", "train")

1.2 The overall (average) treatment effect

Before looking for heterogeneity, we estimate the overall treatment effect of the trial: the difference in the event rate between the two arms (absolute risk difference, ARD) and the odds ratio. Both HTE analyses below should average back to roughly this number.

# event rate by treatment arm;
overall <- indo %>%
  group_by(rx) %>%
  summarise(n = n(), events = sum(outcome), event_rate = mean(outcome), .groups = "drop")
overall
# A tibble: 2 × 4
     rx     n events event_rate
  <int> <int>  <int>      <dbl>
1     0   307     52     0.169 
2     1   294     27     0.0918
# absolute risk difference (treated - control) with a 95% Wald confidence interval;
p1 <- overall$event_rate[overall$rx == 1]; n1 <- overall$n[overall$rx == 1]
p0 <- overall$event_rate[overall$rx == 0]; n0 <- overall$n[overall$rx == 0]
ARD_overall <- p1 - p0
se_overall  <- sqrt(p1 * (1 - p1) / n1 + p0 * (1 - p0) / n0)
c(ARD = ARD_overall, lower = ARD_overall - 1.96 * se_overall, upper = ARD_overall + 1.96 * se_overall)
        ARD       lower       upper 
-0.07754437 -0.13093271 -0.02415604 
# odds ratio from an unadjusted logistic regression;
glm(outcome ~ rx, data = indo, family = binomial) %>%
  tbl_regression(exponentiate = TRUE)
Characteristic OR 95% CI p-value
rx 0.50 0.30, 0.81 0.006
Abbreviations: CI = Confidence Interval, OR = Odds Ratio

2. Risk-based HTE analysis

2.1 Step 1: a treatment-blind outcome risk model and the risk score

  • We fit a logistic regression of the outcome on the baseline covariates without the treatment in the model, so that the predicted risk reflects baseline risk only.

  • The risk score of a patient is the linear predictor of this model (the log-odds of the outcome, predict(..., type = "link")), centred at its mean; this is the prognostic index (PI) of the lecture.

  • In a real analysis, the risk model should be pre-specified (which variables, which form) and ideally validated; here we keep all covariates for simplicity.

# outcome ~ age + risk + gender + ... (all covariates, no rx);
risk_formula <- reformulate(covariates, response = "outcome")
risk_formula
outcome ~ age + risk + gender + sod + pep + recpanc + psphinc + 
    precut + difcan + paninj + asa + sodsom + bsphinc + bstent + 
    chole + train
risk_model <- glm(risk_formula, data = indo, family = binomial)
summary(risk_model)

Call:
glm(formula = risk_formula, family = binomial, data = indo)

Coefficients:
             Estimate Std. Error z value Pr(>|z|)    
(Intercept) -3.717127   1.014570  -3.664 0.000249 ***
age          0.002292   0.011126   0.206 0.836758    
risk         0.998877   0.447973   2.230 0.025763 *  
gender       0.104782   0.359077   0.292 0.770432    
sod         -0.622085   0.508628  -1.223 0.221305    
pep          0.077874   0.526669   0.148 0.882452    
recpanc     -0.457586   0.358885  -1.275 0.202303    
psphinc     -0.330524   0.533223  -0.620 0.535349    
precut      -0.898827   0.672453  -1.337 0.181340    
difcan      -0.741625   0.513565  -1.444 0.148719    
paninj      -0.122011   0.446974  -0.273 0.784875    
asa         -0.025352   0.501523  -0.051 0.959684    
sodsom      -0.552573   0.357454  -1.546 0.122139    
bsphinc      0.178201   0.288961   0.617 0.537435    
bstent       0.015613   0.542894   0.029 0.977057    
chole        0.932204   0.558188   1.670 0.094908 .  
train        0.608712   0.265496   2.293 0.021863 *  
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 467.73  on 600  degrees of freedom
Residual deviance: 437.13  on 584  degrees of freedom
AIC: 471.13

Number of Fisher Scoring iterations: 5
# risk score = linear predictor (log-odds), centred at the mean;
indo$risk_score <- predict(risk_model, type = "link") - mean(predict(risk_model, type = "link"))

# Rank patients by risk score and group into quintiles (1 = lowest risk, 5 = highest risk);
indo$riskgp <- cut(
  indo$risk_score,
  breaks = quantile(indo$risk_score, probs = seq(0, 1, by = 0.2)),
  include.lowest = TRUE,
  labels = 1:5
)

# observed event rate by risk group: the groups should show increasing risk;
indo %>%
  group_by(riskgp) %>%
  summarise(n = n(), events = sum(outcome), event_rate = round(mean(outcome), 3), .groups = "drop")
# A tibble: 5 × 4
  riskgp     n events event_rate
  <fct>  <int>  <int>      <dbl>
1 1        121      4      0.033
2 2        120     12      0.1  
3 3        120     12      0.1  
4 4        120     20      0.167
5 5        120     31      0.258

2.2 Step 2: the treatment effect within each risk group

  • We fit a logistic regression with treatment, risk group, and their interaction. The interaction test asks whether the relative effect (odds ratio) of indomethacin is the same across risk groups.

  • Writing the model as riskgp + riskgp:rx (instead of rx * riskgp) makes R return one treatment coefficient per risk group, so the group-specific odds ratios can be read directly from the output.

# models without and with the rx x risk group interaction;
model_main <- glm(outcome ~ rx + riskgp, data = indo, family = binomial)
model_int  <- glm(outcome ~ rx * riskgp, data = indo, family = binomial)

# likelihood ratio test for the interaction;
anova(model_main, model_int, test = "LRT")
Analysis of Deviance Table

Model 1: outcome ~ rx + riskgp
Model 2: outcome ~ rx * riskgp
  Resid. Df Resid. Dev Df Deviance Pr(>Chi)
1       595     427.54                     
2       591     427.03  4  0.50568   0.9729
# group-specific odds ratio of rx: one coefficient per risk group;
model_gp <- glm(outcome ~ riskgp + riskgp:rx, data = indo, family = binomial)
tbl_regression(model_gp, exponentiate = TRUE)
Characteristic OR 95% CI p-value
riskgp


    1 — —
    2 2.58 0.71, 12.2 0.2
    3 3.11 0.82, 15.1 0.11
    4 5.83 1.78, 26.4 0.008
    5 10.0 3.17, 44.4 <0.001
riskgp * rx


    1 * rx 0.35 0.02, 2.83 0.4
    2 * rx 0.67 0.17, 2.28 0.5
    3 * rx 0.51 0.14, 1.70 0.3
    4 * rx 0.40 0.13, 1.07 0.079
    5 * rx 0.45 0.19, 1.03 0.064
Abbreviations: CI = Confidence Interval, OR = Odds Ratio
# put the group-specific OR and 95% CI in a small table for plotting;
or_by_group <- broom::tidy(model_gp, exponentiate = TRUE, conf.int = TRUE) %>%
  filter(str_detect(term, ":rx")) %>%                      # keep the 5 rx terms only;
  mutate(riskgp = factor(1:5)) %>%
  select(riskgp, OR = estimate, lower_CI = conf.low, upper_CI = conf.high)
or_by_group
# A tibble: 5 × 4
  riskgp    OR lower_CI upper_CI
  <fct>  <dbl>    <dbl>    <dbl>
1 1      0.351   0.0171     2.83
2 2      0.674   0.171      2.28
3 3      0.510   0.143      1.70
4 4      0.396   0.131      1.07
5 5      0.449   0.188      1.03
# Plot the group-specific rx effects on the OR scale;
ggplot(or_by_group, aes(x = OR, y = riskgp)) +
  geom_point(size = 3) +
  geom_errorbarh(aes(xmin = lower_CI, xmax = upper_CI), height = 0.2) +
  geom_vline(xintercept = 1, linetype = "dashed") +
  scale_x_log10() +
  xlab("Odds Ratio (Treatment Effect), log scale") +
  ylab("Risk group (1 = lowest risk)") +
  theme_minimal()

2.3 The absolute treatment effect within each risk group

The lecture showed that even with a constant odds ratio, the absolute benefit grows with baseline risk. Here we compute the observed absolute risk difference (ARD) within each risk group directly from the event rates, with the number needed to treat (NNT = 1/|ARD|).

ard_by_group <- indo %>%
  group_by(riskgp, rx) %>%
  summarise(n = n(), events = sum(outcome), p = mean(outcome), .groups = "drop") %>%
  # one row per risk group with the treated (_1) and control (_0) columns side by side;
  pivot_wider(names_from = rx, values_from = c(n, events, p)) %>%
  mutate(
    ARD      = p_1 - p_0,                                           # treated minus control;
    se       = sqrt(p_1 * (1 - p_1) / n_1 + p_0 * (1 - p_0) / n_0),  # Wald standard error;
    lower_CI = ARD - 1.96 * se,
    upper_CI = ARD + 1.96 * se,
    NNT      = round(1 / abs(ARD))
  )

ard_by_group %>% mutate(across(c(p_0, p_1, ARD, se, lower_CI, upper_CI), ~ round(.x, 3)))
# A tibble: 5 × 12
  riskgp   n_0   n_1 events_0 events_1   p_0   p_1    ARD    se lower_CI
  <fct>  <int> <int>    <int>    <int> <dbl> <dbl>  <dbl> <dbl>    <dbl>
1 1         63    58        3        1 0.048 0.017 -0.03  0.032   -0.093
2 2         70    50        8        4 0.114 0.08  -0.034 0.054   -0.14 
3 3         52    68        7        5 0.135 0.074 -0.061 0.057   -0.173
4 4         62    58       14        6 0.226 0.103 -0.122 0.066   -0.253
5 5         60    60       20       11 0.333 0.183 -0.15  0.079   -0.304
# ℹ 2 more variables: upper_CI <dbl>, NNT <dbl>
ggplot(ard_by_group, aes(x = ARD, y = riskgp)) +
  geom_point(size = 3) +
  geom_errorbarh(aes(xmin = lower_CI, xmax = upper_CI), height = 0.2) +
  geom_vline(xintercept = 0, linetype = "dashed") +
  xlab("Absolute risk difference (treated - control); below 0 = benefit") +
  ylab("Risk group (1 = lowest risk)") +
  theme_minimal()

3. Effect-based HTE analysis with a causal forest

3.1 Missing covariate data: multiple imputation

  • A causal forest needs complete covariate data. Dropping patients with missing values (complete-case analysis) loses information and can bias the results, so we use multiple imputation: each missing value is filled in m times with plausible values, giving m completed data sets. The analysis is repeated on each data set and the results are combined.

  • The imputation model should include the outcome and the treatment, so that the imputed covariates keep their relationships with them.

  • The indomethacin data set is complete, so for demonstration only we make 10% of age and risk missing at random. (Delete that chunk when your own data already have missing values.)

# FOR DEMONSTRATION ONLY: introduce 10% missing values at random in age and risk;
set.seed(2026)
indo_mis <- indo
indo_mis$age[sample(1:nrow(indo_mis), size = round(0.10 * nrow(indo_mis)))]  <- NA
indo_mis$risk[sample(1:nrow(indo_mis), size = round(0.10 * nrow(indo_mis)))] <- NA

# number of missing values per variable;
colSums(is.na(indo_mis[, c("outcome", "rx", covariates)]))
outcome      rx     age    risk  gender     sod     pep recpanc psphinc  precut 
      0       0      60      60       0       0       0       0       0       0 
 difcan  paninj     asa  sodsom bsphinc  bstent   chole   train 
      0       0       0       0       0       0       0       0 
# multiple imputation with chained equations (mice);
# - m = 5 completed data sets;
# - method = "pmm" (predictive mean matching): imputed values are borrowed from observed values,
#   so a 0/1 variable stays 0/1 and age stays within the observed range;
# - the imputation model includes the outcome and rx together with all covariates;
imp <- mice(indo_mis[, c("outcome", "rx", covariates)],
            m = 5, method = "pmm", seed = 2026, printFlag = FALSE)

imp$method   # "pmm" for variables that had missing values, "" for complete variables;
outcome      rx     age    risk  gender     sod     pep recpanc psphinc  precut 
     ""      ""   "pmm"   "pmm"      ""      ""      ""      ""      ""      "" 
 difcan  paninj     asa  sodsom bsphinc  bstent   chole   train 
     ""      ""      ""      ""      ""      ""      ""      "" 
# the first completed data set (mice::complete, written in full because tidyr also has a complete() function);
indo_imp1 <- mice::complete(imp, 1)
colSums(is.na(indo_imp1))   # no missing values left;
outcome      rx     age    risk  gender     sod     pep recpanc psphinc  precut 
      0       0       0       0       0       0       0       0       0       0 
 difcan  paninj     asa  sodsom bsphinc  bstent   chole   train 
      0       0       0       0       0       0       0       0 

3.2 Tune the causal forest with grf’s built-in tuning

A forest has several tuning parameters.

  • The most important one is the minimum number of patients in a leaf (min.node.size): small leaves let the forest find fine-grained heterogeneity but also fit noise; large leaves are stable but may miss real heterogeneity.

  • The others are sample.fraction (share of patients used to grow each tree), mtry (number of covariates tried at each split), honesty.fraction (share of each tree’s sample used to choose the splits, the rest estimates the leaf effects), honesty.prune.leaves, alpha and imbalance.penalty (how unbalanced a split may be).

With tune.parameters = "all", grf chooses these values by cross-validation inside the forest:

  1. it draws 50 random candidate settings and fits a small forest (200 trees) for each;
  2. it scores each candidate with the out-of-bag R-loss: every patient’s treatment effect is predicted by the trees that did not use that patient (this is the held-out part), and a good effect model is one where, after removing the average outcome and the average treatment assignment, (treatment - average treatment) x (predicted effect) explains the outcome well. We never observe a patient’s true treatment effect, so this is the criterion used in place of a prediction error;
  3. it fits a smooth model to the scores to find the most promising region, refits there, and keeps the tuned setting only if it beats grf’s default setting.

The seed makes the random search reproducible. We tune once here on the first imputed data set to look at the selected values; in the next section each imputed data set is tuned in the same way.

# data: imputed data set 1;
X1 <- as.matrix(indo_imp1[, covariates])   # covariate matrix (patients x covariates);
Y1 <- indo_imp1$outcome                    # outcome (0/1);
W1 <- indo_imp1$rx                         # treatment (0/1);
n  <- nrow(X1)

cf_tuned <- causal_forest(X1, Y1, W1,
                          num.trees       = 1000, 
                          honesty         = TRUE,
                          tune.parameters = "all",    # grf's built-in cross-validated tuning;
                          seed            = 2026)

unlist(cf_tuned$tunable.params)   # the selected values;
     sample.fraction                 mtry        min.node.size 
          0.05993474           2.00000000          24.00000000 
    honesty.fraction honesty.prune.leaves                alpha 
          0.57127886           0.00000000           0.14257270 
   imbalance.penalty 
          0.64057081 

3.3 The final causal forest in each imputed data set

In each of the m imputed data sets we fit the final honest forest, tuned by grf, and save:

  • the out-of-bag predicted treatment effect of every patient (predict(cf)), i.e., the ITE (here a conditional absolute risk difference, cARD) predicted by the trees that did not use that patient, with its variance;
  • the average treatment effect (ATE) estimated by the forest;
  • the variable importance;
  • the leaf size selected by the tuning, to check that the imputed data sets agree.
m <- imp$m   # number of imputed data sets;

# containers for the results: one column per imputed data set;
tau_mat <- matrix(NA, nrow = n, ncol = m)   # ITE of each patient;
var_mat <- matrix(NA, nrow = n, ncol = m)   # variance of the ITE;
ate_tab <- data.frame(imputation = 1:m, estimate = NA, std.err = NA, min.node.size = NA)   # ATE, SE, tuned leaf size;
vi_mat  <- matrix(NA, nrow = length(covariates), ncol = m, dimnames = list(covariates, NULL))

for (i in 1:m) {
  
  # completed data set i;
  dat_i <- mice::complete(imp, i)
  X_i <- as.matrix(dat_i[, covariates])
  Y_i <- dat_i$outcome
  W_i <- dat_i$rx
  
  # final honest causal forest, tuned by grf on this data set;
  cf_i <- causal_forest(X_i, Y_i, W_i,
                        num.trees       = 2000,
                        honesty         = TRUE,
                        tune.parameters = "all",
                        seed            = 2026)
  
  # out-of-bag ITE and its variance for every patient;
  pred_i <- predict(cf_i, estimate.variance = TRUE)
  tau_mat[, i] <- pred_i$predictions
  var_mat[, i] <- pred_i$variance.estimates
  
  # ATE estimated by the forest, and the tuned leaf size;
  ate_i <- average_treatment_effect(cf_i)
  ate_tab$estimate[i]      <- ate_i["estimate"]
  ate_tab$std.err[i]       <- ate_i["std.err"]
  ate_tab$min.node.size[i] <- cf_i$tunable.params$min.node.size
  
  # variable importance;
  vi_mat[, i] <- variable_importance(cf_i)
  
  # keep the forest of the first data set for the calibration test below;
  if (i == 1) cf_1 <- cf_i
}

ate_tab
  imputation    estimate    std.err min.node.size
1          1 -0.07936198 0.02718325             2
2          2 -0.07920276 0.02721799             3
3          3 -0.08374583 0.02716770            24
4          4 -0.07999841 0.02712202             2
5          5 -0.08098044 0.02705007             2

3.4 Combine the results across the imputed data sets

Rubin’s rules: the pooled estimate is the average over the m data sets; the pooled variance is the average within-imputation variance plus (1 + 1/m) times the between-imputation variance of the estimates.

# pooled ITE of each patient and its standard error;
indo$tau    <- rowMeans(tau_mat)                           # average over the m data sets;
within_var  <- rowMeans(var_mat)                           # average within-imputation variance;
between_var <- apply(tau_mat, 1, var)                      # variance of the m estimates;
indo$tau_se <- sqrt(within_var + (1 + 1 / m) * between_var)

summary(indo$tau)
    Min.  1st Qu.   Median     Mean  3rd Qu.     Max. 
-0.08761 -0.08361 -0.08298 -0.08290 -0.08223 -0.07818 
summary(indo$tau_se)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
0.02306 0.02872 0.02998 0.03006 0.03125 0.03785 
# distribution of the predicted ITE (negative = predicted benefit);
ggplot(indo, aes(x = tau)) +
  geom_histogram(bins = 30, fill = "grey70", colour = "white") +
  geom_vline(xintercept = 0, linetype = "dashed") +
  labs(x = "Predicted individual treatment effect (cARD); below 0 = benefit", y = "Patients") +
  theme_minimal()

# pooled ATE from the forest, to be compared with the trial's overall risk difference in Section 1.2;
ate_pooled <- mean(ate_tab$estimate)
ate_se     <- sqrt(mean(ate_tab$std.err^2) + (1 + 1 / m) * var(ate_tab$estimate))
c(ATE = ate_pooled, lower = ate_pooled - 1.96 * ate_se, upper = ate_pooled + 1.96 * ate_se)
        ATE       lower       upper 
-0.08065788 -0.13401849 -0.02729727 
c(ARD_overall = ARD_overall)
ARD_overall 
-0.07754437 
  • With the tuned forest, every patient receives almost the same predicted effect, close to the overall ATE: the forest found no heterogeneity it could predict from the baseline covariates.

3.5 Is there heterogeneity? The calibration test

test_calibration() regresses the outcome on the forest’s out-of-bag predictions (on the first imputed data set here; check the others as well):

  • mean.forest.prediction close to 1 means the average prediction is right;
  • differential.forest.prediction close to 1 with a small one-sided p-value means the forest captures real heterogeneity (patients predicted to benefit more do benefit more). A p-value near 1 means no evidence of heterogeneity. When the predictions have almost no spread (as here), the coefficient itself becomes unstable and should not be over-interpreted; the p-value is what matters.
test_calibration(cf_1)

Best linear fit using forest predictions (on held-out data)
as well as the mean forest prediction as regressors, along
with one-sided heteroskedasticity-robust (HC3) SEs:

                                 Estimate Std. Error  t value    Pr(>t)    
mean.forest.prediction            0.92636    0.24999   3.7056 0.0001152 ***
differential.forest.prediction -238.05960   16.00649 -14.8727 1.0000000    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

3.6 Group patients by predicted benefit and check the observed effect in each group

The natural next step is to rank patients by predicted benefit, form quintiles, and compare the observed treatment effect in each quintile (event rate in treated minus event rate in control) with the predicted one.

Repeated split-sample validation (as in Goligher et al). The remedy is to judge the predictions on patients the forest has never seen:

  1. split the patients at random into two halves;
  2. fit the forest on one half (including the tuning, so that the whole model-building procedure is repeated) and predict the ITE of the patients in the other (held-out) half;
  3. form quintiles of predicted benefit within the held-out half and compute the observed ARD in each quintile;
  4. repeat many times and average the results over the splits.

Within a held-out half, all patients share the same forest, so their ranking depends only on their covariates, not on their outcomes. Because each forest is tuned, this chunk takes a couple of minutes (5 splits in each of the 5 imputed data sets, 50 forests); increase n_rep for a final analysis.

set.seed(2026)
n_rep  <- 5              # number of random splits per imputed data set;
n_half <- round(n / 2)    # size of the fitting half;

# containers: one row per (imputed data set, split), one column per quintile;
pred_q <- matrix(NA, nrow = m * n_rep, ncol = 5)   # mean predicted ITE in the held-out quintile;
obs_q  <- matrix(NA, nrow = m * n_rep, ncol = 5)   # observed ARD in the held-out quintile;
row    <- 0                                        # row counter;

for (i in 1:m) {
  
  dat_i <- mice::complete(imp, i)
  X_i <- as.matrix(dat_i[, covariates])
  Y_i <- dat_i$outcome
  W_i <- dat_i$rx
  
  for (r in 1:n_rep) {
    
    row <- row + 1
    
    # random half for fitting the forest, the other half is held out;
    fit_half  <- sample(1:n, size = n_half)
    test_half <- setdiff(1:n, fit_half)
    
    # tuned forest on the fitting half;
    cf_half <- causal_forest(X_i[fit_half, ], Y_i[fit_half], W_i[fit_half],
                             num.trees       = 1000,
                             honesty         = TRUE,
                             tune.parameters = "all",
                             tune.num.reps   = 20,     # candidate settings tried by the tuning search (default 50);
                             tune.num.trees  = 100)    # trees per candidate forest (default 200);               
    
    # predicted ITE for the held-out patients: this forest never saw their outcomes;
    tau_test <- predict(cf_half, X_i[test_half, ])$predictions
    Y_test   <- Y_i[test_half]
    W_test   <- W_i[test_half]
    
    # quintiles of predicted benefit within the held-out half (1 = largest predicted benefit);
    q_test <- ntile(rank(tau_test, ties.method = "random"), 5)
    
    # mean predicted ITE and observed ARD (treated - control) in each quintile;
    pred_q[row, ] <- tapply(tau_test, q_test, mean)
    obs_q[row, ]  <- tapply(Y_test[W_test == 1], q_test[W_test == 1], mean) -
                     tapply(Y_test[W_test == 0], q_test[W_test == 0], mean)
  }
}

# summarise over the splits: mean predicted and observed effect per quintile,
# with the 2.5th and 97.5th percentiles of the observed effect across splits;
validation <- data.frame(
  quintile       = factor(1:5),
  predicted_cARD = colMeans(pred_q),
  observed_ARD   = colMeans(obs_q),
  lower          = apply(obs_q, 2, quantile, probs = 0.025),
  upper          = apply(obs_q, 2, quantile, probs = 0.975)
)
validation %>% mutate(across(-quintile, ~ round(.x, 3)))
  quintile predicted_cARD observed_ARD  lower upper
1        1         -0.081       -0.062 -0.206 0.050
2        2         -0.077       -0.068 -0.239 0.033
3        3         -0.074       -0.064 -0.261 0.128
4        4         -0.070       -0.109 -0.218 0.040
5        5         -0.066       -0.127 -0.310 0.024
ggplot(validation, aes(y = quintile)) +
  geom_errorbarh(aes(xmin = lower, xmax = upper), height = 0.2) +
  geom_point(aes(x = observed_ARD, shape = "Observed ARD in held-out half",
                 colour = "Observed ARD in held-out half"), size = 3) +
  geom_point(aes(x = predicted_cARD, shape = "Predicted cARD (mean)",
                 colour = "Predicted cARD (mean)"), size = 3) +
  geom_vline(xintercept = 0, linetype = "dashed") +
  scale_shape_manual(values = c(16, 4), name = NULL) +
  scale_colour_manual(values = c("black", "red"), name = NULL) +
  labs(x = "Absolute risk difference (treated - control); below 0 = benefit",
       y = "Quintile of predicted benefit (1 = largest predicted benefit)",
       title = "Predicted versus observed treatment effect, repeated split-sample validation",
       caption = "Error bars: 2.5th to 97.5th percentile of the observed ARD across the random splits") +
  theme_minimal() +
  theme(legend.position = "bottom")

  • If the forest had found real heterogeneity, the observed effects would decrease (more benefit) from quintile 5 to quintile 1, following the predicted effects.

  • Here the predicted effects differ little across quintiles and the observed effects scatter around the overall ATE: no reproducible heterogeneity in this trial.

  • A forest with small leaves and no tuning would predict a wider range of ITEs, but this validation would show the same flat observed effects; tuning and held-out validation are what keep us from reporting noise as a finding.

3.7 Which covariates drive the heterogeneity?

Variable importance measures how often the forest split on each covariate (weighted toward splits near the top of the trees). Covariates with high importance are the ones the forest used to separate patients with different treatment effects. Averaged over the imputed data sets:

vi <- data.frame(covariate = covariates, importance = rowMeans(vi_mat)) %>%
  arrange(desc(importance))
vi
        covariate importance
risk         risk 0.07024390
age           age 0.03512195
asa           asa 0.03512195
gender     gender 0.00000000
sod           sod 0.00000000
pep           pep 0.00000000
recpanc   recpanc 0.00000000
psphinc   psphinc 0.00000000
precut     precut 0.00000000
difcan     difcan 0.00000000
paninj     paninj 0.00000000
sodsom     sodsom 0.00000000
bsphinc   bsphinc 0.00000000
bstent     bstent 0.00000000
chole       chole 0.00000000
train       train 0.00000000
ggplot(vi, aes(x = importance, y = reorder(covariate, importance))) +
  geom_col(fill = "grey60") +
  labs(x = "Variable importance (average over imputations)", y = NULL) +
  theme_minimal()

  • The few splits the tuned forest makes involve mainly age and a handful of procedural factors, but since the predicted effects barely differ between patients, this ranking should not be read as evidence of effect modification.