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:
a risk-based analysis, where patients are grouped by their predicted baseline risk from a treatment-blind prognostic model
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.
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 forestlibrary(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)
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.
# 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
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")
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
# 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 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 <- indoindo_mis$age[sample(1:nrow(indo_mis), size =round(0.10*nrow(indo_mis)))] <-NAindo_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)]))
# 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;
# 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;
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:
it draws 50 random candidate settings and fits a small forest (200 trees) for each;
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;
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.
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 in1: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
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:
split the patients at random into two halves;
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;
form quintiles of predicted benefit within the held-out half and compute the observed ARD in each quintile;
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 in1:m) { dat_i <- mice::complete(imp, i) X_i <-as.matrix(dat_i[, covariates]) Y_i <- dat_i$outcome W_i <- dat_i$rxfor (r in1: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)))
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
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.