Intermediate

The tidymodels Framework

Learn the modern, tidy approach to machine learning in R using recipes, parsnip, workflows, tune, and yardstick.

tidymodels Overview

tidymodels is a collection of packages for ML that follow tidyverse principles. It provides a consistent, modular interface for the entire modeling process.

PackagePurpose
rsampleData splitting and resampling (train/test, cross-validation)
recipesFeature engineering and preprocessing
parsnipUnified model specification (model-agnostic API)
workflowsBundle recipes + models into a single object
tuneHyperparameter tuning
yardstickModel evaluation metrics

Creating a Recipe (Preprocessing)

R
library(tidymodels)

# Define preprocessing steps
rec <- recipe(mpg ~ ., data = mtcars) |>
  step_normalize(all_numeric_predictors()) |>    # Scale numeric
  step_dummy(all_nominal_predictors()) |>       # Encode categoricals
  step_corr(all_numeric_predictors()) |>       # Remove correlated
  step_zv(all_predictors())                     # Remove zero-variance

# Common recipe steps:
# step_normalize()  - center and scale
# step_log()        - log transform
# step_impute_mean() - impute missing values
# step_pca()        - PCA dimensionality reduction
# step_interact()   - create interaction terms

Setting a Model Spec (parsnip)

parsnip provides a unified interface - change the engine without changing your code:

R
# Linear regression
lm_spec <- linear_reg() |>
  set_engine("lm")

# Random forest (switch engine easily)
rf_spec <- rand_forest(trees = 500) |>
  set_engine("ranger") |>
  set_mode("regression")

# XGBoost
xgb_spec <- boost_tree(trees = 500, tree_depth = 6) |>
  set_engine("xgboost") |>
  set_mode("regression")

Building Workflows

R
# Combine recipe + model into a workflow
wf <- workflow() |>
  add_recipe(rec) |>
  add_model(rf_spec)

Complete Pipeline Example

R
library(tidymodels)

# 1. Split data
set.seed(42)
split <- initial_split(mtcars, prop = 0.75)
train <- training(split)
test <- testing(split)

# 2. Define recipe
rec <- recipe(mpg ~ ., data = train) |>
  step_normalize(all_numeric_predictors())

# 3. Define model
rf_spec <- rand_forest(trees = 500) |>
  set_engine("ranger", importance = "impurity") |>
  set_mode("regression")

# 4. Build workflow
wf <- workflow() |>
  add_recipe(rec) |>
  add_model(rf_spec)

# 5. Fit the model
fit <- wf |> fit(data = train)

# 6. Predict on test data
predictions <- fit |> predict(test)

# 7. Evaluate
results <- test |>
  bind_cols(predictions) |>
  metrics(truth = mpg, estimate = .pred)

print(results)
# .metric  .estimator  .estimate
# rmse     standard     2.15
# rsq      standard     0.89
# mae      standard     1.72
Key insight: The power of tidymodels is composability. You can swap the model (line 3) without changing anything else. The recipe, workflow, and evaluation code stay exactly the same.

Ready to Go Deeper?

Live instructor-led courses from our partners. Affiliate disclosure.