tidymodels-overview
This skill should be used when working with R tidymodels packages, including when the user asks to "create a tidymodels workflow", "build a recipe", "tune a model", "use parsnip", "set up resampling", "create a workflow_set", "compare models", "stack models", or mentions tidymodels packages like recipes, parsnip, workflows, workflowsets, tune, rsample, yardstick, or stacks. Provides ecosystem context before package-specific skills.
What this skill does
# Tidymodels Overview
The tidymodels ecosystem provides a consistent, modular framework for machine learning in R. Understanding the ecosystem context helps when working with any tidymodels pipeline before diving into package-specific details.
## Core Principle: Recipes Are Plans, Not Actions
**Critical**: A `recipe` object is a *specification* of preprocessing steps. Adding steps like `step_normalize()` does **not** transform data immediately. Transformations execute only when:
1. `prep()` estimates parameters from training data
2. `bake()` applies the prepped recipe to new data
```r
# This does NOT transform data - it creates a plan
rec <- recipe(outcome ~ ., data = train) |>
step_normalize(all_numeric_predictors())
# This estimates parameters (means, sds) from training data
prepped <- prep(rec, training = train)
# This applies transformations to new data
processed <- bake(prepped, new_data = test)
```
## The Tidymodels Workflow
Follow this standard workflow for modeling projects:
### 1. Data Splitting (rsample)
Allocate data to training, validation, and test sets before any modeling:
```r
set.seed(123)
data_split <- initial_split(data, prop = 0.8, strata = outcome)
train_data <- training(data_split)
test_data <- testing(data_split)
# For iterative evaluation during development
resamples <- vfold_cv(train_data, v = 10)
```
### 2. Preprocessing (recipes)
Define feature engineering as a recipe specification:
```r
rec_spec <- recipe(outcome ~ ., data = train_data) |>
step_normalize(all_numeric_predictors()) |>
step_dummy(all_factor_predictors()) |>
step_zv(all_predictors())
```
Use tidyselect helpers for column selection:
- `all_predictors()`, `all_outcomes()` - by role
- `all_numeric_predictors()`, `all_nominal_predictors()` - by type and role
- `has_role()`, `has_type()` - explicit queries
### 3. Model Specification (parsnip)
Define the model type, engine, and mode separately from fitting:
```r
model_spec <- rand_forest(mtry = tune(), trees = 1000) |>
set_engine("ranger") |>
set_mode("regression")
```
### 4. Bundling (workflows)
Combine preprocessing and model into a single object:
```r
wflow <- workflow() |>
add_recipe(rec_spec) |>
add_model(model_spec)
```
### 5. Evaluation (tune + yardstick)
Use resampling or validation sets to assess performance:
```r
# Define metrics
metrics <- metric_set(rmse, rsq, mae)
# Tune hyperparameters
tuned <- tune_grid(
wflow,
resamples = resamples,
grid = 10,
metrics = metrics
)
# Select best parameters
best_params <- select_best(tuned, metric = "rmse")
```
### 6. Finalization
Finalize the workflow and fit to full training data:
```r
final_wflow <- finalize_workflow(wflow, best_params)
final_fit <- last_fit(final_wflow, split = data_split)
# Extract test set metrics
collect_metrics(final_fit)
```
## Package Roles
| Package | Purpose | Key Functions |
|---------|---------|---------------|
| **rsample** | Data splitting and resampling | `initial_split()`, `vfold_cv()`, `bootstraps()` |
| **recipes** | Preprocessing specification | `recipe()`, `step_*()`, `prep()`, `bake()` |
| **parsnip** | Model specification | Model functions, `set_engine()`, `set_mode()` |
| **workflows** | Bundle recipe + model | `workflow()`, `add_recipe()`, `add_model()` |
| **tune** | Hyperparameter optimization | `tune_grid()`, `tune_bayes()`, `select_best()` |
| **yardstick** | Performance metrics | `metric_set()`, `rmse()`, `accuracy()` |
| **workflowsets** | Compare multiple pipelines | `workflow_set()`, `workflow_map()` |
| **stacks** | Model ensembling | `stacks()`, `add_candidates()`, `blend_predictions()` |
| **hardhat** | Internal infrastructure | `mold()`, `forge()`, blueprints |
## Key Principles
### Use Package Functions, Not Direct Access
Never directly modify tidymodels object internals. Always use provided functions:
```r
# WRONG - directly modifying internals
recipe_obj$steps[[1]]$means <- new_means
# CORRECT - use proper functions
rec <- recipe(...) |>
step_normalize(...) |>
prep()
```
### Use Selectors, Not String Matching
Avoid constructing variable lists manually:
```r
# WRONG - manual string matching
numeric_cols <- names(data)[sapply(data, is.numeric)]
rec |> step_normalize(all_of(numeric_cols))
# CORRECT - use tidyselect helpers
rec |> step_normalize(all_numeric_predictors())
```
### Understand Role Requirements
Custom roles are required at `bake()` time by default. When using `step_rm()` with custom roles, update requirements:
```r
rec <- recipe(...) |>
update_role(id_column, new_role = "id") |>
update_role_requirements("id", bake = FALSE) |>
step_rm(has_role("id"))
```
### workflowsets Require Same Outcome
All workflows in a `workflow_set` must predict the same outcome variable. For different outcomes, create separate workflow sets.
## When to Use Each Package
- **Simple model**: recipes + parsnip + workflows
- **Hyperparameter tuning**: Add tune
- **Model comparison**: Add workflowsets
- **Ensemble models**: Add stacks (requires `save_pred = TRUE`, `save_workflow = TRUE`)
- **Custom preprocessing interfaces**: Use hardhat
## Additional Resources
### Reference Files
For detailed information, consult:
- **`references/packages.md`** - Detailed package documentation including object structures, creation processes, and deep knowledge links
- **`references/common-problems.md`** - Common pitfalls when working with tidymodels and how to avoid them
### External Documentation
- [tidymodels.org](https://www.tidymodels.org) - Official documentation and tutorials
- [recipes.tidymodels.org](https://recipes.tidymodels.org) - Recipe step reference
- [parsnip.tidymodels.org](https://parsnip.tidymodels.org) - Model specifications
Related in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.