How to do it...

This recipe shows you how to use the rpart package to build classification trees and the rpart.plot package to generate nice-looking tree diagrams:

  1. Load the rpart, rpart.plot, and caret packages:
> library(rpart) 
> library(rpart.plot) 
> library(caret) 
  1. Read the data:
> bn <- read.csv("banknote-authentication.csv") 
  1. Create data partitions. We need two partitions--training and validation. Rather than copying the data in the partitions, we will just keep the indices of the cases that represent the training cases and subset as and when needed:
> set.seed(1000) 
> train.idx <- createDataPartition(bn$class, p = 0.7, list = FALSE)
  1. Build the tree with the following code:
> mod <- rpart(class ~ ., data = bn[train.idx, ], method ...

Get R Data Analysis Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.