Search code examples
decision-treeextractrpartparty

decision tree in R- extract data from a specific branch


I am trying to build a classify decision tree using rpart and partykit, and I am wondering is there any function within those packages (or any packages, for that matter) to allow me to create a dataset containing data from a specific subtree or branch?

I know that I can manually create the subset from original data set with DT rules, but I am trying to automate certain process and finding that function will help me immensely.

Example:

library (rpart)
library(partykit)

data("Titanic", package = "datasets")
ttnc <- as.data.frame(Titanic)
ttnc <- ttnc[rep(1:nrow(ttnc), ttnc$Freq), 1:4]
names(ttnc)[2] <- "Gender"

rp <- rpart(Survived ~ Gender + Age + Class,  data = ttnc)
prp <- as.party(rp)

prp[5]

Lets say that I wanna extract data from the subtree #5, is there any function within those packages that allow me to do that?

Thank you!


Solution

  • In addition to the solution posted by @JakobGepp you can use the data_party() function provided by partykit:

    data_party(prp, id = 5)
    

    Essentially, this does the same thing internally that Jakob did explicitly by hand.