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 ...

Get R Data Analysis Cookbook - Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.