# Regression trees and CART, by hand
# https://tidyecology.com/posts/regression-trees-and-cart/
#
# The R code of this Tidy Ecology tutorial, chunk by chunk, in the order of the post.
# Run it top to bottom in a fresh R session. Code the post shows but does not run
# is commented out. The prose, and the numbers it quotes, are in the post itself.
# Post last modified: 2026-10-15

## ---- setup ----
library(rpart)
library(ggplot2)

## house theme
te_ink<-"#16241d"; te_body<-"#2c3a31"; te_forest<-"#275139"; te_label<-"#46604a"
te_paper<-"#f5f4ee"; te_line<-"#dad9ca"; te_faint<-"#5d6b61"
te_gold<-"#cda23f"; te_green<-"#2f8f63"; te_red<-"#b5534e"; te_lowc<-"#c9b458"; te_highc<-"#1d5b4e"
theme_te<-function(base_size=12){
  theme_minimal(base_size=base_size)+
  theme(text=element_text(colour=te_body),
    plot.title=element_text(colour=te_ink,size=rel(1.05)),
    plot.subtitle=element_text(colour=te_faint,size=rel(0.9)),
    axis.title=element_text(colour=te_label), axis.text=element_text(colour=te_faint),
    panel.grid.major=element_line(colour=te_line,linewidth=0.3), panel.grid.minor=element_blank(),
    plot.background=element_rect(fill="#f5f4ee",colour=NA), panel.background=element_rect(fill="#f5f4ee",colour=NA),
    legend.position="bottom", strip.text=element_text(colour=te_ink))
}

set.seed(4310)
n <- 240
x1 <- runif(n, 0, 10)   # temperature
x2 <- runif(n, 0, 10)   # moisture
f  <- ifelse(x1 < 5, 2 + 0.9*x2, 11 - 0.8*x2) + 1.2*(x1 > 7)*(x2 > 6)
sigma <- 2.0
y  <- f + rnorm(n, 0, sigma)
dat <- data.frame(y, x1, x2, f)

set.seed(99); tr <- sample(n, 160); te <- setdiff(1:n, tr)
rmse <- function(a, b) sqrt(mean((a - b)^2))

## ---- hand-cart ----
sse <- function(v) if (length(v) == 0) 0 else sum((v - mean(v))^2)

best_split <- function(d, minbucket = 10) {
  base <- sse(d$y); best <- NULL; bestgain <- 0
  for (v in c("x1", "x2")) {
    xs <- d[[v]]; cand <- sort(unique(xs)); cand <- (head(cand, -1) + tail(cand, -1)) / 2
    for (s in cand) {
      L <- d$y[xs <= s]; R <- d$y[xs > s]
      if (length(L) < minbucket || length(R) < minbucket) next
      gain <- base - sse(L) - sse(R)
      if (gain > bestgain) { bestgain <- gain; best <- list(var = v, split = s, gain = gain) }
    }
  }
  best
}

grow <- function(d, depth = 0, maxdepth = 3, minsplit = 20, minbucket = 10) {
  if (nrow(d) < minsplit || depth >= maxdepth) return(list(leaf = TRUE, pred = mean(d$y)))
  bs <- best_split(d, minbucket)
  if (is.null(bs)) return(list(leaf = TRUE, pred = mean(d$y)))
  idx <- d[[bs$var]] <= bs$split
  list(leaf = FALSE, var = bs$var, split = bs$split, gain = bs$gain,
       left = grow(d[idx, , drop = FALSE], depth + 1, maxdepth, minsplit, minbucket),
       right = grow(d[!idx, , drop = FALSE], depth + 1, maxdepth, minsplit, minbucket))
}
predict_tree <- function(node, nd) {
  out <- numeric(nrow(nd))
  for (i in seq_len(nrow(nd))) { nn <- node
    while (!nn$leaf) nn <- if (nd[[nn$var]][i] <= nn$split) nn$left else nn$right
    out[i] <- nn$pred }
  out
}

ht <- grow(dat, maxdepth = 3)
root_var  <- ht$var
root_split<- round(ht$split, 3)
root_gain <- round(ht$gain, 1)
deep      <- round(c(ht$left$left$split, ht$left$right$split), 2)   # two levels below the root

## ---- cart-check ----
rp <- rpart(y ~ x1 + x2, data = dat, method = "anova",
            control = rpart.control(maxdepth = 3, minsplit = 20, minbucket = 10, cp = 0, xval = 0))
rp_root_split <- round(rp$splits[1, "index"], 3)
max_diff <- signif(max(abs(predict_tree(ht, dat) - predict(rp, dat))), 3)
n_leaves <- length(unique(round(predict_tree(ht, dat), 6)))

## ---- fp-guard-1 ----
stopifnot(max_diff / max(1, abs(predict(rp, dat))) < 1e-10)

## ---- partition ----
lsplit <- ht$left$split; rsplit <- ht$right$split
ggplot(dat, aes(x1, x2, colour = y)) +
  geom_point(size = 1.9, alpha = 0.9) +
  scale_colour_gradient(low = te_lowc, high = te_highc, name = "biomass") +
  annotate("segment", x = ht$split, xend = ht$split, y = 0, yend = 10,
           colour = te_red, linewidth = 0.8) +
  annotate("segment", x = 0, xend = ht$split, y = lsplit, yend = lsplit,
           colour = te_ink, linewidth = 0.6, linetype = "22") +
  annotate("segment", x = ht$split, xend = 10, y = rsplit, yend = rsplit,
           colour = te_ink, linewidth = 0.6, linetype = "22") +
  labs(title = "A regression tree cuts the space into boxes",
       subtitle = "Root split on temperature (red), then a moisture split inside each side (dashed)",
       x = "temperature", y = "moisture") +
  theme_te()

## ---- bias-variance ----
stump  <- rpart(y ~ x1 + x2, data = dat[tr, ], method = "anova",
                control = rpart.control(maxdepth = 1, xval = 0))
full   <- rpart(y ~ x1 + x2, data = dat[tr, ], method = "anova",
                control = rpart.control(cp = 0, minsplit = 4, minbucket = 2, xval = 0))
set.seed(2020)
grid   <- rpart(y ~ x1 + x2, data = dat[tr, ], method = "anova",
                control = rpart.control(cp = 0, minsplit = 10, minbucket = 5, xval = 10))
cpt <- grid$cptable
im  <- which.min(cpt[, "xerror"]); se <- cpt[im, "xerror"] + cpt[im, "xstd"]
i1  <- which(cpt[, "xerror"] <= se)[1]
pruned <- prune(grid, cp = cpt[i1, "CP"])

lv <- function(m) sum(m$frame$var == "<leaf>")
tr_full<-round(rmse(predict(full,dat[tr,]),dat$y[tr]),3);  te_full<-round(rmse(predict(full,dat[te,]),dat$y[te]),3)
tr_prun<-round(rmse(predict(pruned,dat[tr,]),dat$y[tr]),3); te_prun<-round(rmse(predict(pruned,dat[te,]),dat$y[te]),3)
te_stmp<-round(rmse(predict(stump,dat[te,]),dat$y[te]),3)
floor_rmse <- round(rmse(dat$f[te], dat$y[te]), 3)
nl_full <- lv(full); nl_prun <- lv(pruned)

## ---- rmse-curve ----
sizes <- sort(unique(pmax(1, cpt[, "nsplit"] + 1)))
cpvals <- cpt[, "CP"]; nsp <- cpt[, "nsplit"]
rows <- lapply(seq_along(cpvals), function(k){
  pk <- prune(grid, cp = cpvals[k])
  data.frame(leaves = lv(pk),
             train = rmse(predict(pk, dat[tr, ]), dat$y[tr]),
             test  = rmse(predict(pk, dat[te, ]), dat$y[te]))
})
curve <- do.call(rbind, rows); curve <- curve[!duplicated(curve$leaves), ]
long <- rbind(data.frame(leaves = curve$leaves, rmse = curve$train, set = "training"),
              data.frame(leaves = curve$leaves, rmse = curve$test,  set = "test"))
mk <- curve[which.min(abs(curve$leaves - nl_prun)), ]
ggplot(long, aes(leaves, rmse, colour = set)) +
  geom_line(linewidth = 0.8) + geom_point(size = 1.2) +
  geom_point(data = data.frame(leaves = mk$leaves, rmse = mk$test),
             aes(leaves, rmse), inherit.aes = FALSE, colour = te_red, size = 3) +
  scale_colour_manual(values = c(training = te_gold, test = te_forest), name = NULL) +
  labs(title = "Training error is not test error",
       subtitle = "Red marker: the tree size chosen by the one-standard-error rule",
       x = "number of leaves", y = "RMSE") +
  theme_te()

## ---- instability ----
set.seed(717); B <- 500; roots <- character(B); rootpt <- numeric(B)
for (b in 1:B) {
  ib <- sample(n, n, replace = TRUE)
  rb <- rpart(y ~ x1 + x2, data = dat[ib, ], method = "anova",
              control = rpart.control(maxdepth = 3, minsplit = 20, minbucket = 10, cp = 0, xval = 0))
  roots[b] <- rownames(rb$splits)[1]; rootpt[b] <- rb$splits[1, "index"]
}
root_tab <- round(prop.table(table(roots)), 3)
pct_x1 <- unname(root_tab["x1"]) * 100
qx1 <- round(quantile(rootpt[roots == "x1"], c(.25, .5, .75)), 2)

## ---- pruning ----
set.seed(2020)
big <- rpart(y ~ x1 + x2, data = dat, method = "anova",
             control = rpart.control(cp = 0, minsplit = 10, minbucket = 5, xval = 10))
cp2 <- big$cptable
jmin <- which.min(cp2[, "xerror"])
j1se <- which(cp2[, "xerror"] <= cp2[jmin, "xerror"] + cp2[jmin, "xstd"])[1]
leaves_min <- cp2[jmin, "nsplit"] + 1
leaves_1se <- cp2[j1se, "nsplit"] + 1
leaves_full <- sum(big$frame$var == "<leaf>")
