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

Generating regression trees for data with categorical predictors

The rpart function works even when a dataset has categorical predictor variables. You just have to ensure that the variable is tagged as a factor. See the following example:

> ed <- read.csv("education.csv") 
> ed$region <- factor(ed$region) 
> set.seed(1000) 
> t.idx <- createDataPartition(ed$expense, p = 0.7, list = FALSE) 
> fit <- rpart(expense ~ region+urban+income+under18, data = ed[t.idx,]) 
> prp(fit, type=2, nn=TRUE, fallen.leaves=TRUE, faclen=4, varlen=8, shadow.col="gray") 

The following output is obtained:

Regression trees can also be built for categorical predictors as ...

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