### in case we haven't installed the necessary libraries # install.packages("rpart") # install.packages("rpart.plot") ########## #Example 1 (on iris) ########## # Load the necessary libraries library(rpart) library(rpart.plot) # Load and inspect the iris dataset data(iris) pairs(iris) # Build a classification decision tree iris_tree <- rpart::rpart(Species ~ ., data = iris, method = "class") # Plot the decision tree rpart.plot(iris_tree, main = "Decision Tree for Iris Species") # Make predictions on the dataset predictions <- predict(iris_tree, iris, type = "class") # Generate confusion matrix conf_mat <- table(Predicted = predictions, Actual = iris$Species) # Display the confusion matrix print(conf_mat) # print model's summary summary(iris_tree) ########## #Example 2 (on mtcars) ########## # Build a regression tree to predict mpg mtcars_tree <- rpart(mpg ~ wt + hp + cyl, data = mtcars, method = "anova") # Plot the regression tree rpart.plot(mtcars_tree, main = "Regression Tree for mpg") # inspect the tree-inferred rules rpart.rules(mtcars_tree) # plot complexity parameter for the fit used in rpart plotcp(mtcars_tree) # Make predictions predicted_mpg <- predict(mtcars_tree, mtcars) # Compare actual vs predicted head(cbind(Actual = mtcars$mpg, Predicted = predicted_mpg)) ########## #Example 3 (plotting the trees with base R) ########## # Basic plot of the tree structure plot(iris_tree, uniform=TRUE, main="Decision Tree Structure") text(iris_tree, use.n=TRUE, all=TRUE, cex=0.8)