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 k-nearest neighbours (kNN) method, follow these steps:

  1. Load the class and caret packages:
> library(class) 
> library(caret) 
  1. Read the data:
> vac <- read.csv("vacation-trip-classification.csv") 
  1. Standardize the predictor variables, Income and Family_size:
> vac$Income.z <- scale(vac$Income) 
> vac$Family_size.z <- scale(vac$Family_size) 
  1. Partition the data. You need three partitions for KNN:
> set.seed(1000) 
> train.idx <- createDataPartition(vac$Result, p = 0.5, list = FALSE) 
> train <- vac[train.idx, ] 
> temp <- vac[-train.idx, ] 
> val.idx <- createDataPartition(temp$Result, p = 0.5, list = FALSE) 
> val <- temp[val.idx, ] 
> test <- temp[-val.idx, ] 
  1. Generate predictions for validation cases ...

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