How to do it...

Perform the following steps to classify data with random forest:

  1. First, you have to install and load the randomForest package:
        > install.packages("randomForest")
        > library(randomForest)  
  1. You can then fit the random forest classifier with a training set:
        > churn.rf = randomForest(churn ~ ., data = trainset, importance        = T)
        > churn.rf
        Output
        Call:
         randomForest(formula = churn ~ ., data = trainset, importance         = T) 
                       Type of random forest: classification
                             Number of trees: 500
        No. of variables tried at each split: 4
    
                OOB estimate of  error rate: 4.88%
        Confusion matrix:
            yes     no class.error
         yes 247   95 0.277777778
        no   18 1955 0.009123163
  1. Next, make predictions based on the fitted model and testing dataset:
    > churn.prediction = predict(churn.rf, ...

Get Machine Learning with R Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.