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

To use random forest models for classification, follow these steps:

  1. Load the randomForest and caret packages:
> library(randomForest) 
> library(caret) 
  1. Read the data and convert the response variable to a factor:
> bn <- read.csv("banknote-authentication.csv") 
> bn$class <- factor(bn$class) 
  1. Select a subset of the data to build the model. In random forests, we do not need to actually partition the data for model evaluation as the tree construction process has partitioning inherent in every step. However, we keep aside some of the data here just to illustrate the process of using the model for prediction and also to get an idea of the model's performance:
> set.seed(1000) > sub.idx <- createDataPartition(bn$class, p=0.7, ...

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