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 build KNN models for regressions, perform the following steps:

  1. Load the dummies, FNN, scales, and caret packages as follows:
> library(dummies) 
> library(FNN) 
> library(scales) > library(caret)
  1. Read the data:
> educ <- read.csv("education.csv") 
  1. Generate dummies for the categorical variable region, and add them to educ as follows:
> dums <- dummy(educ$region, sep="_") 
> educ <- cbind(educ, dums) 
  1. Because KNN performs distance computations, we should either rescale or standardize the predictors. In the present example, we have three numeric predictors and a categorical predictor in the form of three dummy variables. Standardizing dummy variables is tricky, and hence, we will scale the numeric ones to [0, 1] and leave ...

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