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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.