Earn the Decision Tree Certificate
Practice the exercises below. When you feel ready, attempt the quiz to earn a verifiable certificate you can share on LinkedIn.
Decision Tree Exercises in R: 15 Practice Problems
Fifteen practice problems on decision trees with rpart: classification, regression, pruning, visualization.
RInteractive R
library(rpart)
library(rpart.plot)
Exercise 1: Classification tree
Show solution
RInteractive R
rpart(Species ~ ., data = iris)
Exercise 2: Regression tree
Show solution
RInteractive R
rpart(mpg ~ ., data = mtcars)
Exercise 3: Plot a tree
Show solution
RInteractive R
fit <- rpart(Species ~ ., data = iris)
rpart.plot(fit)
Exercise 4: Adjust cp
Show solution
RInteractive R
rpart(Species ~ ., data = iris, control = rpart.control(cp = 0.01))
Exercise 5: Adjust minsplit
Show solution
RInteractive R
rpart(Species ~ ., data = iris, control = rpart.control(minsplit = 5))
Exercise 6: Predict probabilities
Show solution
RInteractive R
fit <- rpart(Species ~ ., data = iris)
head(predict(fit, iris, type = "prob"))
Exercise 7: Predict class
Show solution
RInteractive R
fit <- rpart(Species ~ ., data = iris)
head(predict(fit, iris, type = "class"))
Exercise 8: Variable importance
Show solution
RInteractive R
fit <- rpart(Species ~ ., data = iris)
fit$variable.importance
Exercise 9: Pruning with printcp
Show solution
RInteractive R
fit <- rpart(mpg ~ ., data = mtcars, cp = 0.001)
printcp(fit)
Exercise 10: Prune to best cp
Show solution
RInteractive R
fit <- rpart(mpg ~ ., data = mtcars, cp = 0.001)
best_cp <- fit$cptable[which.min(fit$cptable[,"xerror"]), "CP"]
prune(fit, cp = best_cp)
Exercise 11: Surrogate splits
Show solution
RInteractive R
fit <- rpart(Species ~ ., data = iris,
control = rpart.control(usesurrogate = 2))
Exercise 12: Tree depth
Show solution
RInteractive R
rpart(Species ~ ., data = iris, control = rpart.control(maxdepth = 3))
Exercise 13: Cross-validated error
Show solution
RInteractive R
fit <- rpart(mpg ~ ., data = mtcars)
fit$cptable
Exercise 14: Compare default vs deep tree
Show solution
RInteractive R
f1 <- rpart(Species ~ ., data = iris)
f2 <- rpart(Species ~ ., data = iris, control = rpart.control(cp = 0.001, minsplit = 2))
list(nodes_default = nrow(f1$frame), nodes_deep = nrow(f2$frame))
Exercise 15: Custom split criteria (Gini)
Show solution
RInteractive R
rpart(Species ~ ., data = iris, parms = list(split = "gini"))
What to do next
- Random-Forest-Exercises (shipped), ensemble of trees.
- XGBoost-Exercises (shipped), gradient-boosted trees.
Ready to earn the Decision Tree Certificate?
The quiz is concept-based and respects your time: pass it once and your verifiable certificate is yours to share on LinkedIn, your resume, or your portfolio. Take it when you feel comfortable with the material.
Attempt the quiz→