O'Reilly logo

R Data Analysis Cookbook - Second Edition by Kuntal Ganguly

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required