Decision trees, using rpart

knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)

source("_threads.R")
library(dplyr)
library(tidypredict)
library(rpart)
set.seed(100)

| Function |Works| |---------------------------------------------------------------|-----| |tidypredict_fit(), tidypredict_sql(), parse_model() | |tidypredict_to_column() | |tidypredict_test() | |tidypredict_interval(), tidypredict_sql_interval() | |parsnip |

How it works

Here is a simple rpart() model using the mtcars dataset:

library(dplyr)
library(tidypredict)
library(rpart)

model <- rpart(mpg ~ ., data = mtcars)

Under the hood

The parser extracts the tree structure from the model's frame and splits components. It handles both numeric and categorical splits, as well as surrogate splits for missing value handling.

model$frame |>
  head()

The output from parse_model() is transformed into a dplyr, a.k.a Tidy Eval, formula. The decision tree becomes a dplyr::case_when() statement.

tidypredict_fit(model)

From there, the Tidy Eval formula can be used anywhere where it can be operated. tidypredict provides three paths:

Classification

rpart classification models are also supported:

model_class <- rpart(Species ~ ., data = iris)
tidypredict_fit(model_class)

parsnip

tidypredict also supports rpart model objects fitted via the parsnip package.

library(parsnip)

parsnip_model <- decision_tree(mode = "regression") |>
  set_engine("rpart") |>
  fit(mpg ~ ., data = mtcars)

tidypredict_fit(parsnip_model)

Categorical predictors

rpart handles categorical predictors natively. The generated formula uses %in% for categorical splits:

mtcars2 <- mtcars
mtcars2$cyl <- factor(mtcars2$cyl)

model_cat <- rpart(mpg ~ cyl + wt + hp, data = mtcars2)
tidypredict_fit(model_cat)

Surrogate splits

rpart uses surrogate splits to handle missing values during prediction. When the primary split variable is missing, the model uses surrogate variables (other variables that produce similar splits) to route the observation. This behavior is controlled by the usesurrogate parameter in rpart.control().



Try the tidypredict package in your browser

Any scripts or data that you put into this service are public.

tidypredict documentation built on Aug. 24, 2026, 9:10 a.m.