Skip to main content
v2026.11,858 entries · CC-BY 4.0

Random Forests in R: randomForest and ranger, Step by Step

Fit random forests in R with randomForest and ranger, read out-of-bag error and variable importance, and see where the two packages’ defaults differ.

Written and maintained by CASRAI Editorial Board

Last updated

Random forests in R are fitted with the randomForest package (the original R port of Breiman and Cutler’s algorithm) or the faster ranger package, both installed from CRAN with install.packages(). A random forest grows many decision trees on resampled data using random subsets of predictors and combines them, which gives a prediction model plus a built-in error estimate that needs no separate test set: the out-of-bag (OOB) error. This guide fits a classification forest and a regression forest, shows where each package reports OOB error and variable importance under different names, and lists the defaults that differ between the two packages. Random forest in R means exactly this workflow, whether you type “random forest in r” or “random forests in r”.

What it is used for in research

A random forest is a supervised learning method for classification (a categorical outcome) and regression (a numeric outcome). The CRAN entry for randomForest describes it as classification and regression “based on a forest of trees that uses random inputs, based on Breiman (2001)”. Researchers use it to build a predictive model when relationships among many predictors are nonlinear or interact, to rank predictors by how much they contribute to prediction, and, in unsupervised mode, to assess proximities among data points. The ranger package adds survival and probability trees and is described on CRAN as “particularly suited for high dimensional data”.

A forest is a prediction tool, not an inference tool: it does not give coefficients, confidence intervals or p-values. If the aim is to test a hypothesis about one predictor, a regression model is usually the better fit. For the wider picture of machine learning in research, including pitfalls, see What Is Machine Learning?; for the same algorithm in Python, see the scikit-learn tutorial.

Install or access (official source only)

Both packages are on CRAN, R’s official package repository. In an R session:

install.packages("randomForest")
install.packages("ranger")
library(randomForest)
library(ranger)

As checked on 2026-10-29, CRAN lists randomForest at version 4.7-1.2, published 2024-09-22, with Breiman and Cutler as original authors, Andy Liaw as maintainer of the R port together with Matthew Wiener. CRAN lists ranger at version 0.18.0, published 2026-01-16. The canonical package pages are CRAN.R-project.org/package=randomForest and cran.r-project.org/web/packages/ranger. Check the version on those pages before citing it.

Step-by-step: fit a random forest in R

1. Fit a classification forest with randomForest

  1. Set a seed so the forest is reproducible, then hold out a test set before fitting anything:
    set.seed(42)
    idx   <- sample(nrow(iris), 0.7 * nrow(iris))
    train <- iris[idx, ]
    test  <- iris[-idx, ]
  2. Fit the forest with the formula interface. Ask for importance explicitly, because the default is importance = FALSE:
    rf <- randomForest(Species ~ ., data = train, importance = TRUE)
    print(rf)
  3. Predict the held-out rows and compare with the truth:
    pred <- predict(rf, newdata = test)
    table(predicted = pred, actual = test$Species)

The documented usage is randomForest(x, y = NULL, xtest = NULL, ytest = NULL, ntree = 500, mtry = ..., nodesize = ..., importance = FALSE, ...), plus a formula method, randomForest(formula, data = NULL, ..., subset, na.action = na.fail). The manual notes that for large data sets with many variables the formula interface is not advised, so switch to the x/y form (randomForest(x = train[, -5], y = train$Species)) when the data grow.

2. Fit a regression forest

The response type decides the mode. The manual states: “If a factor, classification is assumed, otherwise regression is assumed.” A numeric outcome therefore gives a regression forest:

set.seed(42)
rf_reg <- randomForest(mpg ~ ., data = mtcars, importance = TRUE)
print(rf_reg)

3. Fit the same model with ranger

set.seed(42)
rg <- ranger(Species ~ ., data = train, num.trees = 500, importance = "permutation")
rg$prediction.error
rg$variable.importance

The documented usage is ranger(formula = NULL, data = NULL, num.trees = 500, mtry = NULL, importance = "none", write.forest = TRUE, probability = FALSE, min.node.size = NULL, ...). Setting probability = TRUE grows probability trees, and the OOB error is then reported as a Brier score.

Output and how to read it

What out-of-bag error means

Each tree is grown on a bootstrap sample, so some rows are left out of that tree. Predicting every row using only the trees that did not see it gives the out-of-bag prediction, and the error of those predictions is the OOB error. The randomForest manual describes its predicted component as “the predicted values of the input data based on out-of-bag samples”. OOB error is computed on the training data, so it is an internal estimate; it does not replace a held-out test set when you need to report performance for a model you will tune further. In particular, do not call an OOB error a “test error” in a methods section.

Where each package reports it

Quantity randomForest ranger
Overall OOB error err.rate (classification): OOB error up to the i-th tree prediction.error: proportion misclassified (classification), Brier score (probability), MSE (regression)
Confusion matrix confusion (classification, OOB) confusion.matrix (classification, OOB)
OOB predictions predicted predictions
Variable importance importance matrix, one row per predictor variable.importance

Reading variable importance

For randomForest, importance(rf) returns a matrix with one row per predictor. Two measures are available through type: type 1 is the mean decrease in accuracy, found by recording the OOB error for each tree, permuting one predictor, recording it again, and averaging the difference over trees; type 2 is the mean decrease in node impurity, the total decrease from splits on the variable averaged over trees (Gini index for classification, residual sum of squares for regression). The scale argument defaults to TRUE and divides permutation-based values by their standard errors. To plot, varImpPlot(rf, sort = TRUE, n.var = min(30, nrow(rf$importance))) draws a dot chart, and returns the plotted importances invisibly.

For ranger, the importance argument takes "none" (the default), "impurity", "impurity_corrected" or "permutation". Impurity is the Gini index for classification and the variance of the responses for regression. Because the impurity and permutation measures answer different questions, state which one you used when you report a ranking.

Defaults that differ between the two packages

Setting randomForest ranger
Number of trees ntree = 500 num.trees = 500
Variables tried at each split mtry: floor(sqrt(p)) for classification, max(floor(p/3), 1) for regression mtry: the number of variables, square-rooted and rounded down
Minimum node size nodesize: 1 for classification, 5 for regression min.node.size: 1 classification, 5 regression, 3 survival, 10 probability
Importance importance = FALSE importance = "none"

Here p is the number of predictors. The defaults differ by outcome type within randomForest itself, which matters if a class label is stored as a number: a numeric label silently switches the model from classification to regression, with the regression defaults.

Troubleshooting

The fit stops with an error about missing values

The randomForest default is na.action = na.fail, so any missing value stops the fit. Remove incomplete rows (na.omit()) or impute. If you impute, do it inside the training data only, after splitting; imputing the whole data set first leaks information from the test rows into the training rows. See data leakage for the general problem.

The importance matrix is missing or empty

Importance is not computed unless you ask for it: pass importance = TRUE to randomForest() (the manual’s example does this before calling importance()), or importance = "permutation" or "impurity" to ranger().

You wanted classification and got regression output

The response is numeric. Convert it with as.factor() before fitting.

The formula interface is slow on wide data

Use the x/y interface for randomForest, or switch to ranger, which CRAN describes as suited to high-dimensional data.

Results change every run

Forests use random sampling. Call set.seed() immediately before fitting and record the package versions; both steps matter for computational reproducibility. Another R workflow that depends on the same habits is meta-analysis in R with metafor.

Free alternatives

Option Language What the official source says
randomForest R “Breiman and Cutlers Random Forests for Classification and Regression”; classification and regression based on Breiman (2001); version 4.7-1.2 on CRAN
ranger R “A Fast Implementation of Random Forests”; classification, regression, survival and probability trees; version 0.18.0 on CRAN
scikit-learn Python Covered in the scikit-learn tutorial, which includes its random forest classes

FAQ

What is the difference between randomForest and ranger?

Both fit random forests and share the 500-tree default, but they name their outputs differently (err.rate and confusion versus prediction.error), set importance through different arguments, and use different minimum-node-size defaults for some outcome types. ranger also supports survival and probability trees.

How do I get variable importance from a random forest in R?

Fit with importance = TRUE in randomForest and call importance() or varImpPlot(), or fit with importance = "permutation" in ranger and read variable.importance.

How many trees should I use?

Both packages default to 500. err.rate in randomForest records OOB error up to the i-th tree, so plotting it shows whether the error has levelled off for your data.

Can a random forest handle missing values?

Not with the randomForest default: na.action = na.fail raises an error on any NA, so remove or impute before fitting.

Is OOB error the same as test error?

No. OOB error is an internal estimate from the rows each tree did not see. Report performance on a held-out set when you tune the model or compare it with others.

Sources (official docs)

Checked on 2026-10-29.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about Random Forests in R: randomForest and ranger, Step by Step

Ask your first 2 questions free below. Subscribers get 150 a day for $29 a month.

An AI assistant specialized in research administration. It cites the sources behind every answer, labels web answers and says when it can't answer.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays free to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →

Ask CASRAI · Regulatory Radar

Research-admin question? Get an answer that links its sources.

An AI assistant specialized in research administration. Every answer links its sources to check before you act. 2 questions free, no account. $29/month after.

  • Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.
  • Every answer numbers its sources and links each one, so you can check the source yourself.