Build terminal-node summary statistics for a fitted tree
Source:R/tree_default_name.R
tree_build_terminal_stats.RdComputes one-row summaries for each terminal node of a fitted tree by first assigning observations to nodes and then applying user-supplied summary functions within each terminal group.
Examples
data(kenya, package = "ineqTrees")
kenya_plot_vars <- c("wealth", "deadu5_num", "rural", "ed", "reg", "unskilled")
kenya_plot_data <- kenya[
stats::complete.cases(kenya[, kenya_plot_vars]),
kenya_plot_vars
]
set.seed(20260512)
kenya_plot_data <- kenya_plot_data[
sample.int(nrow(kenya_plot_data), 800L),
,
drop = FALSE
]
kenya_plot_fit <- ci_tree(
cbind(wealth, deadu5_num) ~ rural + ed + reg + unskilled,
data = kenya_plot_data,
rank_name = "wealth",
outcome_name = "deadu5_num",
control = ci_tree_control(
minsplit = 100,
minbucket = 50,
minprob = 0.05,
maxdepth = 3
)
)
kenya_stat_funs <- list(
n = nrow,
mortality = function(df) mean(df$deadu5_num),
mean_wealth = function(df) mean(df$wealth)
)
tree_build_terminal_stats(
kenya_plot_fit,
kenya_plot_data,
stat_funs = kenya_stat_funs
)
#> node_id n mortality mean_wealth
#> 1 4 109 0.00000000 0.10045582
#> 2 5 132 0.02272727 0.31801860
#> 3 6 137 0.02919708 -0.23154495
#> 4 9 209 0.04784689 0.04196376
#> 5 10 127 0.15748031 -0.38363010
#> 6 11 86 0.24418605 -0.90504013