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 classify using the Naive Bayes method, follow these steps:

  1. Load the e1071 and caret packages:
> library(e1071) 
> library(caret) 
  1. Read the data:
> ep <- read.csv("electronics-purchase.csv") 
  1. Partition the data:
> set.seed(1000) 
> train.idx <- createDataPartition(ep$Purchase, p = 0.67, list = FALSE) 
  1. Build the model:
> epmod <- naiveBayes(Purchase ~ . , data = ep[train.idx,]) 
  1. Look at the model:
> epmod 
  1. Predict for each case of the validation partition:
> pred <- predict(epmod, ep[-train.idx,]) 
  1. Create the classification table for the validation partition and generate a confusion matrix from it:
> tab <- table(ep[-train.idx,]$Purchase, pred, dnn = c("Actual", "Predicted")) > confusionMatrix(tab)Confusion Matrix ...

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