Description Usage Arguments Value Note Author(s) References See Also Examples
randomForest
implements Breiman's random forest algorithm (based on
Breiman and Cutler's original Fortran code) for classification and
regression. It can also be used in unsupervised mode for assessing
proximities among data points.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17  ## S3 method for class 'formula'
randomForest(formula, data=NULL, ..., subset, na.action=na.fail)
## Default S3 method:
randomForest(x, y=NULL, xtest=NULL, ytest=NULL, ntree=500,
mtry=if (!is.null(y) && !is.factor(y))
max(floor(ncol(x)/3), 1) else floor(sqrt(ncol(x))),
replace=TRUE, classwt=NULL, cutoff, strata,
sampsize = if (replace) nrow(x) else ceiling(.632*nrow(x)),
nodesize = if (!is.null(y) && !is.factor(y)) 5 else 1,
maxnodes = NULL,
importance=FALSE, localImp=FALSE, nPerm=1,
proximity, oob.prox=proximity,
norm.votes=TRUE, do.trace=FALSE,
keep.forest=!is.null(y) && is.null(xtest), corr.bias=FALSE,
keep.inbag=FALSE, ...)
## S3 method for class 'randomForest'
print(x, ...)

data 
an optional data frame containing the variables in the model.
By default the variables are taken from the environment which

subset 
an index vector indicating which rows should be used. (NOTE: If given, this argument must be named.) 
na.action 
A function to specify the action to be taken if NAs are found. (NOTE: If given, this argument must be named.) 
x, formula 
a data frame or a matrix of predictors, or a formula
describing the model to be fitted (for the

y 
A response vector. If a factor, classification is assumed,
otherwise regression is assumed. If omitted, 
xtest 
a data frame or matrix (like 
ytest 
response for the test set. 
ntree 
Number of trees to grow. This should not be set to too small a number, to ensure that every input row gets predicted at least a few times. 
mtry 
Number of variables randomly sampled as candidates at each
split. Note that the default values are different for
classification (sqrt(p) where p is number of variables in 
replace 
Should sampling of cases be done with or without replacement? 
classwt 
Priors of the classes. Need not add up to one. Ignored for regression. 
cutoff 
(Classification only) A vector of length equal to number of classes. The ‘winning’ class for an observation is the one with the maximum ratio of proportion of votes to cutoff. Default is 1/k where k is the number of classes (i.e., majority vote wins). 
strata 
A (factor) variable that is used for stratified sampling. 
sampsize 
Size(s) of sample to draw. For classification, if sampsize is a vector of the length the number of strata, then sampling is stratified by strata, and the elements of sampsize indicate the numbers to be drawn from the strata. 
nodesize 
Minimum size of terminal nodes. Setting this number larger causes smaller trees to be grown (and thus take less time). Note that the default values are different for classification (1) and regression (5). 
maxnodes 
Maximum number of terminal nodes trees in the forest
can have. If not given, trees are grown to the maximum possible
(subject to limits by 
importance 
Should importance of predictors be assessed? 
localImp 
Should casewise importance measure be computed?
(Setting this to 
nPerm 
Number of times the OOB data are permuted per tree for assessing variable importance. Number larger than 1 gives slightly more stable estimate, but not very effective. Currently only implemented for regression. 
proximity 
Should proximity measure among the rows be calculated? 
oob.prox 
Should proximity be calculated only on “outofbag” data? 
norm.votes 
If 
do.trace 
If set to 
keep.forest 
If set to 
corr.bias 
perform bias correction for regression? Note: Experimental. Use at your own risk. 
keep.inbag 
Should an 
... 
optional parameters to be passed to the low level function

An object of class randomForest
, which is a list with the
following components:
call 
the original call to 
type 
one of 
predicted 
the predicted values of the input data based on outofbag samples. 
importance 
a matrix with 
importanceSD 
The “standard errors” of the permutationbased
importance measure. For classification, a 
localImp 
a p by n matrix containing the casewise importance
measures, the [i,j] element of which is the importance of ith
variable on the jth case. 
ntree 
number of trees grown. 
mtry 
number of predictors sampled for spliting at each node. 
forest 
(a list that contains the entire forest; 
err.rate 
(classification only) vector error rates of the prediction on the input data, the ith element being the (OOB) error rate for all trees up to the ith. 
confusion 
(classification only) the confusion matrix of the prediction (based on OOB data). 
votes 
(classification only) a matrix with one row for each input data point and one column for each class, giving the fraction or number of (OOB) ‘votes’ from the random forest. 
oob.times 
number of times cases are ‘outofbag’ (and thus used in computing OOB error estimate) 
proximity 
if 
mse 
(regression only) vector of mean square errors: sum of squared
residuals divided by 
rsq 
(regression only) “pseudo Rsquared”: 1  
test 
if test set is given (through the 
The forest
structure is slightly different between
classification and regression. For details on how the trees are
stored, see the help page for getTree
.
If xtest
is given, prediction of the test set is done “in
place” as the trees are grown. If ytest
is also given, and
do.trace
is set to some positive integer, then for every
do.trace
trees, the test set error is printed. Results for the
test set is returned in the test
component of the resulting
randomForest
object. For classification, the votes
component (for training or test set data) contain the votes the cases
received for the classes. If norm.votes=TRUE
, the fraction is
given, which can be taken as predicted probabilities for the classes.
For large data sets, especially those with large number of variables,
calling randomForest
via the formula interface is not advised:
There may be too much overhead in handling the formula.
The “local” (or casewise) variable importance is computed as follows: For classification, it is the increase in percent of times a case is OOB and misclassified when the variable is permuted. For regression, it is the average increase in squared OOB residuals when the variable is permuted.
Andy Liaw andy\_liaw@merck.com and Matthew Wiener matthew\_wiener@merck.com, based on original Fortran code by Leo Breiman and Adele Cutler.
Breiman, L. (2001), Random Forests, Machine Learning 45(1), 532.
Breiman, L (2002), “Manual On Setting Up, Using, And Understanding Random Forests V3.1”, https://www.stat.berkeley.edu/~breiman/Using_random_forests_V3.1.pdf.
predict.randomForest
, varImpPlot
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57  ## Classification:
##data(iris)
set.seed(71)
iris.rf < randomForest(Species ~ ., data=iris, importance=TRUE,
proximity=TRUE)
print(iris.rf)
## Look at variable importance:
round(importance(iris.rf), 2)
## Do MDS on 1  proximity:
iris.mds < cmdscale(1  iris.rf$proximity, eig=TRUE)
op < par(pty="s")
pairs(cbind(iris[,1:4], iris.mds$points), cex=0.6, gap=0,
col=c("red", "green", "blue")[as.numeric(iris$Species)],
main="Iris Data: Predictors and MDS of Proximity Based on RandomForest")
par(op)
print(iris.mds$GOF)
## The `unsupervised' case:
set.seed(17)
iris.urf < randomForest(iris[, 5])
MDSplot(iris.urf, iris$Species)
## stratified sampling: draw 20, 30, and 20 of the species to grow each tree.
(iris.rf2 < randomForest(iris[1:4], iris$Species,
sampsize=c(20, 30, 20)))
## Regression:
## data(airquality)
set.seed(131)
ozone.rf < randomForest(Ozone ~ ., data=airquality, mtry=3,
importance=TRUE, na.action=na.omit)
print(ozone.rf)
## Show "importance" of variables: higher value mean more important:
round(importance(ozone.rf), 2)
## "x" can be a matrix instead of a data frame:
set.seed(17)
x < matrix(runif(5e2), 100)
y < gl(2, 50)
(myrf < randomForest(x, y))
(predict(myrf, x))
## "complicated" formula:
(swiss.rf < randomForest(sqrt(Fertility) ~ .  Catholic + I(Catholic < 50),
data=swiss))
(predict(swiss.rf, swiss))
## Test use of 32level factor as a predictor:
set.seed(1)
x < data.frame(x1=gl(53, 10), x2=runif(530), y=rnorm(530))
(rf1 < randomForest(x[3], x[[3]], ntree=10))
## Grow no more than 4 nodes per tree:
(treesize(randomForest(Species ~ ., data=iris, maxnodes=4, ntree=30)))
## test proximity in regression
iris.rrf < randomForest(iris[1], iris[[1]], ntree=101, proximity=TRUE, oob.prox=FALSE)
str(iris.rrf$proximity)

randomForest 4.612
Type rfNews() to see new features/changes/bug fixes.
Call:
randomForest(formula = Species ~ ., data = iris, importance = TRUE, proximity = TRUE)
Type of random forest: classification
Number of trees: 500
No. of variables tried at each split: 2
OOB estimate of error rate: 5.33%
Confusion matrix:
setosa versicolor virginica class.error
setosa 50 0 0 0.00
versicolor 0 46 4 0.08
virginica 0 4 46 0.08
setosa versicolor virginica MeanDecreaseAccuracy MeanDecreaseGini
Sepal.Length 6.04 7.85 7.93 11.51 8.77
Sepal.Width 4.40 1.03 5.44 5.40 2.19
Petal.Length 21.76 31.33 29.64 32.94 42.54
Petal.Width 22.84 32.67 31.68 34.50 45.77
[1] 0.7282700 0.7903363
Call:
randomForest(x = iris[1:4], y = iris$Species, sampsize = c(20, 30, 20))
Type of random forest: classification
Number of trees: 500
No. of variables tried at each split: 2
OOB estimate of error rate: 5.33%
Confusion matrix:
setosa versicolor virginica class.error
setosa 50 0 0 0.00
versicolor 0 47 3 0.06
virginica 0 5 45 0.10
Call:
randomForest(formula = Ozone ~ ., data = airquality, mtry = 3, importance = TRUE, na.action = na.omit)
Type of random forest: regression
Number of trees: 500
No. of variables tried at each split: 3
Mean of squared residuals: 303.8304
% Var explained: 72.31
%IncMSE IncNodePurity
Solar.R 11.09 10534.24
Wind 23.50 43833.13
Temp 42.03 55218.05
Month 4.07 2032.65
Day 2.63 7173.19
Call:
randomForest(x = x, y = y)
Type of random forest: classification
Number of trees: 500
No. of variables tried at each split: 2
OOB estimate of error rate: 45%
Confusion matrix:
1 2 class.error
1 30 20 0.4
2 25 25 0.5
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
Levels: 1 2
Call:
randomForest(formula = sqrt(Fertility) ~ .  Catholic + I(Catholic < 50), data = swiss)
Type of random forest: regression
Number of trees: 500
No. of variables tried at each split: 1
Mean of squared residuals: 0.3207372
% Var explained: 45.54
Courtelary Delemont FranchesMnt Moutier Neuveville Porrentruy
8.544219 8.977287 9.118769 8.781467 8.522875 8.924009
Broye Glane Gruyere Sarine Veveyse Aigle
8.888588 9.140677 8.952968 8.875341 9.114092 7.936236
Aubonne Avenches Cossonay Echallens Grandson Lausanne
8.328221 8.229574 8.023034 8.274981 8.434141 7.742152
La Vallee Lavaux Morges Moudon Nyone Orbe
7.598992 8.180066 7.987572 8.354154 7.860249 7.873372
Oron Payerne Paysd'enhaut Rolle Vevey Yverdon
8.483563 8.551495 8.410619 8.035697 7.846781 8.363983
Conthey Entremont Herens Martigwy Monthey St Maurice
8.844938 8.657802 8.776533 8.570825 8.892461 8.477949
Sierre Sion Boudry La Chauxdfnd Le Locle Neuchatel
8.919503 8.664517 8.277097 8.033753 8.170280 7.760338
Val de Ruz ValdeTravers V. De Geneve Rive Droite Rive Gauche
8.553581 8.152936 6.781376 7.500274 7.194497
Call:
randomForest(x = x[3], y = x[[3]], ntree = 10)
Type of random forest: regression
Number of trees: 10
No. of variables tried at each split: 1
Mean of squared residuals: 1.49581
% Var explained: 34.99
[1] 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4
num [1:150, 1:150] 1 0.337 0.327 0.356 0.891 ...
 attr(*, "dimnames")=List of 2
..$ : chr [1:150] "1" "2" "3" "4" ...
..$ : chr [1:150] "1" "2" "3" "4" ...
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.