Skip to main content
v2026.11,858 entries · CC-BY 4.0
LAC HealthMedical & Research SuppliesReagents, PPE & instruments — chain-of-custody documented.Fast, traceable sourcing built for regulated research environments, from bench consumables to instrumentation.Shop lac.us CodeCASRAIlac.us

Machine Learning in R: Tidymodels Workflow Guide

Run a tidymodels split, fit, predict and resampling workflow in R with the official commands, and read the .pred and metric tibbles it returns.

Written and maintained by CASRAI Editorial Board

Last updated

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 source only)

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.

  1. Load the packages and data.
    library(tidymodels)
    library(modeldata)
    data(cells, package = "modeldata")
  2. Split into training and test sets. initial_split() makes the split; training() and testing() extract the two parts. strata = class keeps 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)
  3. 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")
  4. Fit on the training data.
    set.seed(234)
    rf_fit <- rf_mod |> fit(class ~ ., data = cell_train)
  5. 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))
  6. Measure performance on the test set.
    rf_testing_pred |> roc_auc(truth = class, .pred_PS)
    rf_testing_pred |> accuracy(truth = class, .pred_class)
  7. 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.

FAQ

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 their source on GitHub. Check each project’s own site for the current materials.

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.

Follow CASRAI

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

Ask CASRAI · free to try

Ask about Machine Learning in R: Tidymodels Workflow Guide

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 →