Written and maintained byCASRAI Editorial Board
Machine learning in R is most often done with the tidymodels collection of packages, which gives one consistent set of functions for splitting data, preprocessing, fitting a model, and measuring how well it predicts. This guide is for researchers and analysts who already have R installed and want a working split, fit, predict and evaluate sequence they can adapt. Commands and output descriptions follow the official tidymodels “Get Started” articles, read 2026-11-07.
What machine learning in R is used for in research
In R, machine learning means fitting a model to a training set and judging it on data the model has not seen, using a modelling package rather than a one-off function per algorithm. The tidymodels project describes itself as a collection of packages for modeling and machine learning that follows tidyverse principles. Its five official Get Started articles cover building a model, preprocessing with recipes, evaluating with resamples, tuning model parameters, and a predictive-modeling case study.
If you are still deciding between supervised and unsupervised approaches, see the supervised vs unsupervised learning comparison. If you are choosing a language, the MATLAB vs R comparison sets the two side by side.
Install or access (official
tidymodels is distributed on CRAN, R’s package repository. The CRAN listing for tidymodels 1.5.0 (published 2026-04-23) shows that it depends on R 4.1 or later and bundles the packages used in the workflow below, including rsample, recipes, parsnip, workflows, tune, dials, yardstick, broom and workflowsets.
install.packages("tidymodels")
library(tidymodels)
The tutorial below also uses the ranger package for its random forest engine and the modeldata package for its example data set. The tidymodels article lists ranger among the packages needed, so install it as well:
install.packages("ranger")
Step-by-step: split, fit, predict and evaluate
These steps reproduce the tidymodels “Evaluate your model with resampling” article, which uses the cells data set from modeldata (a tibble of 2,019 rows and 58 columns) to classify cells as well segmented or poorly segmented.
- Load the packages and data.
library(tidymodels) library(modeldata) data(cells, package = "modeldata") - Split into training and test sets.
initial_split()makes the split;training()andtesting()extract the two parts.strata = classkeeps the class proportions similar in both.set.seed(123) cell_split <- initial_split(cells |> select(-case), strata = class) cell_train <- training(cell_split) cell_test <- testing(cell_split) - Specify the model. A parsnip specification states the model type, the computational engine and the mode, separately from fitting.
rf_mod <- rand_forest(trees = 1000) |> set_engine("ranger") |> set_mode("classification") - Fit on the training data.
set.seed(234) rf_fit <- rf_mod |> fit(class ~ ., data = cell_train) - Predict on the test data. The article binds the class prediction, the class probabilities and the true class into one table.
rf_testing_pred <- predict(rf_fit, cell_test) |> bind_cols(predict(rf_fit, cell_test, type = "prob")) |> bind_cols(cell_test |> select(class)) - Measure performance on the test set.
rf_testing_pred |> roc_auc(truth = class, .pred_PS) rf_testing_pred |> accuracy(truth = class, .pred_class) - Resample the training data for a less optimistic estimate. Bundle model and formula in a workflow, build 10 cross-validation folds with
vfold_cv(), and fit across them.rf_wf <- workflow() |> add_model(rf_mod) |> add_formula(class ~ .) set.seed(345) folds <- vfold_cv(cell_train, v = 10) set.seed(456) rf_fit_rs <- rf_wf |> fit_resamples(folds) collect_metrics(rf_fit_rs)
Adding preprocessing with recipes
When predictors need transformation, the “Preprocess your data with recipes” article defines the transformations once in a recipe and attaches it to the workflow, so the same steps are applied at fit and predict time:
flights_rec <-
recipe(arr_delay ~ ., data = train_data) |>
update_role(flight, time_hour, new_role = "ID") |>
step_date(date, features = c("dow", "month")) |>
step_dummy(all_nominal_predictors()) |>
step_zv(all_predictors())
flights_wflow <-
workflow() |>
add_model(logistic_reg() |> set_engine("glm")) |>
add_recipe(flights_rec)
That excerpt is abridged from the article, which also adds a holiday step and builds the flight data first.
Output and how to read it
| Function | What it returns (per the tidymodels articles) | How to read it |
|---|---|---|
fit() on a specification |
A fitted object whose print header reads “parsnip model object” | The model is trained; pass it to predict() |
predict() |
A tibble with a .pred column for regression, or .pred_class for classification; type = "prob" gives one probability column per class, such as .pred_PS |
Row order matches the new data, so it can be bound back with bind_cols() |
roc_auc(), accuracy() |
A one-row tibble with .metric, .estimator and .estimate |
.estimate is the metric value on the data you passed in |
vfold_cv() |
A 10-row tibble for v = 10, with a splits list column and an id column (Fold01 to Fold10) |
Each row is one analysis/assessment split |
collect_metrics() after fit_resamples() |
One row per metric with .metric, .estimator, mean, n, std_err, .config |
mean averages the metric across folds; std_err shows how much it varied |
Comparing the resampled mean with the test-set value from step 6 is the point of the resampling step in the tidymodels article: the resampled estimate comes from the training data only, so the test set stays untouched until you are ready to report.
Troubleshooting
tidymodels will not install
CRAN lists R 4.1 or later as a dependency of tidymodels 1.5.0, so upgrade R first if install.packages("tidymodels") reports that the package is unavailable for your version.
The engine is not the one you expected
The specification, not the fit, records the engine. Printing a specification shows a line such as “Computational engine: keras” after set_engine("keras"), so print rf_mod before fitting to confirm the model type, engine and mode are what you intended.
Results change between runs
Data splitting, fold creation and random forests all use random numbers. The tidymodels articles call set.seed() before each of these steps; do the same and record the package versions so another analyst can repeat the run. See the computational reproducibility definition for what a repeatable analysis requires.
Free alternatives: tidymodels and caret
Both packages are free and on CRAN. caret is the older of the two; its documentation site is dated 2019-03-27, while the tidymodels CRAN release above is from 2026.
| Package | Documented scope | Source |
|---|---|---|
| tidymodels | Installs and loads a collection of modeling packages that follow tidyverse design; articles cover splitting, recipes, resampling and tuning | CRAN; tidymodels.org |
| caret (Classification And REgression Training) | Data splitting, pre-processing, feature selection, tuning by resampling and variable importance, behind a uniform interface across modelling functions | topepo.github.io/caret |
For one model family in depth, the random forests in R guide continues from here, and running a t-test in R covers a classical test in the same environment.
How do I learn machine learning in R?
Work through the five tidymodels Get Started articles in order (build a model, preprocess with recipes, evaluate with resamples, tune model parameters, predictive modeling case study), running each code block yourself. The steps above cover the first three stages in condensed form.
What are examples of machine learning in R?
The official articles give worked examples: a linear regression of urchin width on initial volume and food regime, a random forest classifying cell segmentation, and a logistic regression predicting flight arrival delays.
Which R package should I use for machine learning?
For new work, tidymodels is the actively released option shown here (version 1.5.0, April 2026). caret remains documented and available on CRAN, so existing code that uses it does not need to be rewritten to run.
Where can I find books and code on GitHub?
The caret project documents the book “Applied Predictive Modeling” among its resources, and both caret and tidymodels publish theirerials
Sources
- tidymodels, “Get Started” and the “Build a model”, “Preprocess your data with recipes” and “Evaluate your model with resamples” articles, tidymodels.org/start, read 2026-11-07.
- CRAN, tidymodels package page (version 1.5.0, published 2026-04-23), cran.r-project.org/web/packages/tidymodels, read 2026-11-07.
- Max Kuhn, caret documentation, topepo.github.io/caret (page dated 2019-03-27), read 2026-11-07.
Research-administration guidance, standards updates and independent tool reviews.