Extracts a subtree with a user-specified number of leaves from an rpart
object.
subtree(tree, leaves = NULL, cv = FALSE)
An rpart
object.
Number of leaves of the desired subtree.
If TRUE
, leaves
is ignored and a cross-validation criterion is used to select a partition.
The subtree, as an rpart
object.
## Generate data.
set.seed(1986)
n <- 3000
k <- 3
X <- matrix(rnorm(n * k), ncol = k)
colnames(X) <- paste0("x", seq_len(k))
Y <- exp(X[, 1]) + 2 * X[, 2] * X[, 2] > 0 + rnorm(n)
## Construct tree.
library(rpart)
tree <- rpart(Y ~ ., data = data.frame(Y, X), cp = 0)
## Extract subtree.
sub_tree <- subtree(tree, leaves = 4)
sub_tree_cv <- subtree(tree, cv = TRUE)