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 random forest models for regression, perform the following steps:

  1. Load the randomForest and caret packages:
> install.packages(c("caret","randomForest"))> library(randomForest) 
> library(caret) 
  1. Read the data:
> bn <- read.csv("BostonHousing.csv") 
  1. Partition the data:
> set.seed(1000) 
> t.idx <- createDataPartition(bh$MEDV, p=0.7, list=FALSE) 
  1. Build the random forest model. Since this command builds many regression trees, it can take significant processing time on even moderate datasets:
> mod <- randomForest(x = bh[t.idx,1:13],  y=bh[t.idx,14],ntree=1000,  xtest = bh[-t.idx,1:13],  ytest = bh[-t.idx,14], importance=TRUE, keep.forest=TRUE) 
  1. Examine the results (your results will most likely differ slightly because ...

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