
r-skills
Skills for R programming covering tidyverse patterns, rlang conditions, targets pipelines, metaprogramming, ggplot2, and tidymodels
- version
- 0.2.0
- GitHub stars
- 17
Install
/plugin install r-skills@r-skillsRun it inside Claude Code after adding the marketplace with /plugin marketplace add jsperger/llm-r-skills.
Contents
Discovered from sourceSkills 9
Tidy R Function Design
Design R functions for humans, not computers. Optimize for cognitive load reduction, predictability, and composability. These principles apply to any R code, not just tidyverse packages.
Core principle: The less a user needs to think to use your function correctly, the better.
Quick Reference
| Design Goal | Pattern |
|---|---|
| Predictable names | Verb in imperative mood, prefixes for families |
| Clear arguments | Most important first, optional with defaults last |
| Pipe-friendly | Primary data as first argument |
| Type stability | Output type predictable from input types |
| Enumerated options | Use arg_match() with character vector defaults |
| Side effects | Return input invisibly; partition from computation |
| Complex strategies | Extract to strategy objects (not boolean flags) |
Function Naming
Use Verbs in Imperative Mood
# Good: imperative verbs
mutate()
filter()
summarize()
# Exception: noun-y builders
geom_point()
recipe()
Prefer Prefixes Over Suffixes
Prefixes enable autocomplete discovery:
# Good: common prefix groups related functions
str_detect(), str_replace(), str_extract()
read_csv(), read_tsv(), read_delim()
# Suffixes for variations on a theme
map_int(), map_chr(), map_dbl()
Length Inversely Proportional to Frequency
# Very frequent -> short
c(), n(), df
# Less frequent -> descriptive
create_bootstrap_samples()
validate_model_specification()
Argument Design
Most Important Arguments First
# Good: transformed data first (pipe-friendly)
str_replace(string, pattern, replacement)
left_join(x, y, by)
# Output-determining args early
read_csv(file, col_types, col_names)
Required Arguments Have No Defaults
# Good: required args have no defaults
my_function <- function(data, columns, method = "default") {
# data and columns required, method optional
}
# Bad: everything has defaults
my_function <- function(data = NULL, columns = NULL, method = "default")
Dots Position Matters
Place ... between required and optional arguments:
# Good: forces explicit naming of optional args
my_function <- function(x, y, ..., verbose = FALSE, na.rm = TRUE) {
# x, y required; anything after ... must be named
}
Keep Defaults Short
Use NULL for complex defaults, compute in body:
# Good: NULL signals "computed if not provided"
my_function <- function(x, weights = NULL) {
weights <- weights %||% rep(1, length(x))
}
# Bad: complex default in signature
my_function <- function(x, weights = rep(1, length(x)))
Enumerate String Options
Use arg_match() with character vector defaults:
my_function <- function(x, method = c("fast", "accurate", "balanced")) {
method <- rlang::arg_match(method)
# method is now validated, first value is default
}
Standardize Common Argument Names
| Purpose | Use | Not |
|---|---|---|
| New data for prediction | new_data | newdata, newData |
| Missing value handling | na_rm | na.rm, rm.na |
| Case weights | weights | wts, w |
| Predictors (data frame) | x | predictors, features |
| Outcome (data frame) | y | response, target |
| Formula interface data | data | df, dataset |
Output Patterns
Type Stability
Output type should be predictable from input types, not values:
# Bad: type depends on VALUE
ifelse(TRUE, 1L, 2) # returns integer
ifelse(FALSE, 1L, 2) # returns double
# Good: type predictable from input types
dplyr::if_else(TRUE, 1L, 2L) # always integer
dplyr::if_else(FALSE, 1L, 2L) # always integer
Tibble Predictions
For modeling functions, predictions should return tibbles:
- Same number of rows as input
- Same row order as input
- Standardized column names:
.pred,.pred_class,.pred_lower
# Good prediction output
predict(model, new_data)
#> # A tibble: 100 x 1
#> .pred
#> <dbl>
#> 1 3.45
#> 2 2.89
Side-Effect Functions Return Invisibly
Functions called for side effects should return the first argument invisibly:
# Good: enables piping
write_csv <- function(x, file, ...) {
# write the file
invisible(x)
}
# Enables this pattern:
data |>
write_csv("backup.csv") |>
filter(important) |>
write_csv("filtered.csv")
Side Effects
Partition Side Effects from Computation
# Bad: computation mixed with side effects
analyze <- function(x) {
result <- expensive_computation(x)
cat("Computed result:", result, "\n") # side effect buried
options(my_option = result) # hidden state change
result
}
# Good: side effects isolated
analyze <- function(x, verbose = FALSE) {
result <- expensive_computation(x)
if (verbose) cli::cli_inform("Computed result: {result}")
result
}
Make Side Effects Easy to Undo
Functions that change global state should return previous values:
# Good: returns previous value for restoration
old <- options(digits = 3)
# ... do work ...
options(old) # restore
Strategy Patterns
Avoid Boolean Strategy Flags
# Bad: boolean flags for strategies
grepl(pattern, x, perl = TRUE, fixed = FALSE, ignore.case = TRUE)
# Which combinations are valid? What does perl + fixed mean?
# Good: strategy objects
str_detect(x, regex(pattern, ignore_case = TRUE))
str_detect(x, fixed(pattern))
Strategy Objects for Complex Options
When strategies need different arguments, create helper functions:
# Strategy helpers with strategy-specific arguments
regex <- function(pattern, ignore_case = FALSE, multiline = FALSE) {
structure(list(pattern = pattern, ignore_case = ignore_case,
multiline = multiline), class = "regex")
}
fixed <- function(pattern) {
structure(list(pattern = pattern), class = "fixed")
}
# Main function accepts strategy objects
str_detect <- function(string, pattern) {
if (inherits(pattern, "regex")) {
# regex-specific handling
} else if (inherits(pattern, "fixed")) {
# fixed-specific handling
}
}
Explicit Over Implicit
Avoid Global Option Dependencies
# Bad: behavior depends on global option
my_function <- function(x) {
na_action <- getOption("na.action") # implicit input
# ...
}
# Good: explicit argument with informative default
my_function <- function(x, na_action = na.omit) {
# ...
}
Inform Users of Important Defaults
When defaults matter, tell the user:
my_function <- function(x, tz = Sys.timezone()) {
if (missing(tz)) {
cli::cli_inform("Using timezone: {.val {tz}}")
}
# ...
}
Model Object Design
Minimize Stored Data
# Bad: stores entire training set
model$training_data <- training_set # memory bloat
# Good: store only what's needed for prediction
model$coefficients <- coefs
model$levels <- factor_levels
Never Save Call Objects
Call objects can embed entire datasets and environments:
# Bad: call may contain data
model$call <- match.call()
# Good: omit call or store only essential info
Use Proper S3 Constructors
# Constructor (internal)
new_my_model <- function(coefficients, levels) {
structure(
list(coefficients = coefficients, levels = levels),
class = "my_model"
)
}
# Validator (internal)
validate_my_model <- function(x) {
stopifnot(is.numeric(x$coefficients))
x
}
# Helper (user-facing)
my_model <- function(...) {
result <- new_my_model(...)
validate_my_model(result)
}
Matrix Subsetting Discipline
Always preserve matrix structure:
# Bad: may return vector
X[, 1]
# Good: always returns matrix
X[, 1, drop = FALSE]
Design Review Checklist
When reviewing R function design:
- Function names are verbs in imperative mood (or nouns for builders)
- Related functions share a prefix
- Most important arguments come first
- Primary data is first argument (pipe-friendly)
- Required arguments have no defaults
-
...comes between required and optional arguments - String options use
arg_match()with enumerated defaults - Output type is predictable from input types
- Side-effect functions return input invisibly
- No hidden dependencies on global options or locale
- Strategy variations use objects, not boolean flags
- Model objects don't store training data or calls
- Matrix subsetting uses
drop = FALSE
Resources
ggplot2 Reference
ggplot2 is an R package for producing visualizations using a grammar of graphics. You compose plots from data, mappings, layers, scales, facets, coordinates, and themes.
Core Components
Data and Mapping
ggplot(data = mpg, mapping = aes(x = cty, y = hwy))
- Data: Tidy data frame (rows = observations, columns = variables)
- Mapping:
aes()links data columns to visual properties (x, y, colour, size, etc.)
Layers
Layers display data using geometry, statistical transformation, and position adjustment:
ggplot(mpg, aes(cty, hwy)) +
geom_point() +
geom_smooth(formula = y ~ x, method = "lm")
Scales
Control how data maps to visual properties and create legends/axes:
ggplot(mpg, aes(cty, hwy, colour = class)) +
geom_point() +
scale_colour_viridis_d()
Facets
Split data into panels by variables:
ggplot(mpg, aes(cty, hwy)) +
geom_point() +
facet_grid(year ~ drv)
Coordinates
Interpret position aesthetics (Cartesian, polar, map projections):
ggplot(mpg, aes(cty, hwy)) +
geom_point() +
coord_fixed()
Theme
Control non-data visual elements:
ggplot(mpg, aes(cty, hwy, colour = class)) +
geom_point() +
theme_minimal() +
theme(legend.position = "top")
ggplot2 4.0 Features
ggplot2 4.0.0 (September 2025) introduced S7 classes and major new features.
S7 Migration
Access properties with @ instead of $:
# ggplot2 4.0+
ggplot()@data
# Deprecated (still works temporarily)
ggplot()$data
Stricter type validation:
element_text(hjust = "foo")
#> Error: @hjust must be <NULL>, <integer>, or <double>, not <character>
Theme-Based Layer Defaults
Ink, Paper, and Accent
Built-in themes accept ink (foreground), paper (background), accent (highlight):
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
geom_smooth(method = "lm", formula = y ~ x) +
theme_gray(paper = "cornsilk", ink = "navy", accent = "tomato")
element_geom() and from_theme()
Set layer defaults via theme(geom):
ggplot(mpg, aes(class, displ)) +
geom_boxplot(aes(colour = from_theme(accent))) +
theme(geom = element_geom(
accent = "tomato",
paper = "cornsilk",
bordertype = "dashed",
borderwidth = 0.2,
linewidth = 2,
linetype = "solid"
))
Theme Palettes
Set default palettes in themes:
theme(
palette.colour.continuous = c("chartreuse", "forestgreen"),
palette.shape.discrete = c("triangle", "triangle open")
)
Theme Shortcuts
New theme_sub_*() functions reduce verbosity:
| Shortcut | Prefix replaced |
|---|---|
theme_sub_axis() | axis.* |
theme_sub_axis_x() | axis.*.x |
theme_sub_axis_bottom() | axis.*.x.bottom |
theme_sub_legend() | legend.* |
theme_sub_panel() | panel.* |
theme_sub_plot() | plot.* |
theme_sub_strip() | strip.* |
# Concise
theme_sub_axis_x(
ticks = element_line(colour = "red"),
ticks.length = unit(5, "mm")
) +
theme_sub_panel(
widths = unit(5, "cm"),
spacing.x = unit(5, "mm")
)
Margin Helpers
margin_auto(1) # all sides = 1
margin_auto(1, 2) # t/b=1, l/r=2
margin_auto(1, 2, 3) # t=1, l/r=2, b=3
margin_part(r = 20) # partial (NA inherits)
Panel Sizes
theme_sub_panel(widths = unit(c(2, 3, 4), "cm")) # per-panel
theme_sub_panel(widths = unit(9, "cm")) # total area
Labels
Label Attributes
Variables with "label" attribute auto-populate axis labels:
attr(df$bill_dep, "label") <- "Bill depth (mm)"
ggplot(df, aes(bill_dep, bill_len)) + geom_point()
Dictionary Labels
dict <- c(species = "Species", bill_dep = "Bill depth (mm)")
ggplot(penguins, aes(bill_dep, bill_len, colour = species)) +
geom_point() +
labs(dictionary = dict)
Function Labels
scale_colour_discrete(name = toupper)
guides(x = guide_axis(title = tools::toTitleCase))
labs(y = \(x) paste0(x, " variable"))
Label hierarchy (lowest to highest): aes() < labs(dictionary) < column attribute < labs() < scale_*(name) < guide_*(title)
Named Breaks
scale_colour_discrete(breaks = c(
"Pygoscelis adeliae" = "Adelie",
"Pygoscelis papua" = "Gentoo"
))
Discrete Scale Improvements
# Palette for spacing
scale_x_discrete(palette = scales::pal_manual(c(1:3, 5:7)))
# Consistent limits across facets
scale_x_discrete(continuous.limits = c(1, 5))
# Minor breaks
scale_x_discrete(
minor_breaks = scales::breaks_width(1, offset = 0.5),
guide = guide_axis(minor.ticks = TRUE)
)
# Secondary axis
scale_x_discrete(sec.axis = dup_axis(
name = "Counts",
breaks = seq_len(7),
labels = paste0("n = ", table(mpg$class))
))
Position Aesthetics
Nudge Aesthetics
geom_text(aes(nudge_x = sign(value) * 3, label = value))
Dodge Order
ggplot(data, aes(x, y, fill = group)) +
geom_boxplot(position = position_dodge(preserve = "single")) +
aes(order = group)
Facets
Wrapping Directions
8 direction options for facet_wrap(dir):
| dir | Start | Fill |
|---|---|---|
"lt" | top-left | left-to-right |
"tl" | top-left | top-to-bottom |
"lb" | bottom-left | left-to-right |
"bl" | bottom-left | bottom-to-top |
"rt" | top-right | right-to-left |
"tr" | top-right | top-to-bottom |
"rb" | bottom-right | right-to-left |
"br" | bottom-right | bottom-to-top |
Free Space
facet_wrap(~ island, scales = "free_x", space = "free_x")
Layer Layout
geom_point(colour = "grey", layout = "fixed_rows") # repeat in rows
geom_point(layout = NULL) # use facet vars
annotate("text", label = "X", layout = 6) # specific panel
Options: NULL, "fixed", <integer>, "fixed_cols", "fixed_rows"
Styling
Boxplot Parts
geom_boxplot(
whisker.linetype = "dashed",
box.colour = "black",
median.linewidth = 2,
staplewidth = 0.5,
staple.colour = "grey50"
)
Violin Quantiles
geom_violin(
quantiles = c(0.1, 0.9),
quantile.linetype = 1,
quantile.colour = "red"
)
Labels
geom_label(
aes(linetype = factor(vs), linewidth = factor(am)),
text.colour = "black",
border.colour = "blue"
)
Varying Fill
geom_area(aes(fill = continuous_var)) # gradient (R 4.1+)
New Stats
stat_manual()
make_centroids <- function(df) {
transform(df, xend = mean(x), yend = mean(y))
}
stat_manual(geom = "segment", fun = make_centroids)
stat_connect()
geom_line(stat = "connect") # stairstep
geom_ribbon(stat = "connect", alpha = 0.4)
# Custom connection shape
smooth <- cbind(x = seq(0, 1, length.out = 20)[-1],
y = scales::rescale(plogis(x, 0.5, 0.1)))
stat_connect(connection = smooth)
Coord Reversal
coord_cartesian(reverse = "x") # "y", "xy", "none"
coord_sf(reverse = "y")
coord_radial(reverse = "theta") # "r", "thetar", "none"
Deprecations
| Old | New |
|---|---|
fatten | median.linewidth / middle.linewidth |
draw_quantiles | quantiles |
geom_errorbarh() | geom_errorbar(orientation = "y") |
coord_trans() | coord_transform() |
borders() | annotation_borders() |
facet_wrap(as.table) | facet_wrap(dir) |
theme_get/set/update/replace() | get/set/update/replace_theme() |
last_plot() | get_last_plot() |
layer_data/grob/scales() | get_layer_data/grob(), get_panel_scales() |
Creating Modeling Packages with hardhat
The hardhat package provides infrastructure for building modeling packages with consistent interfaces. It standardizes preprocessing via mold() (training) and forge() (prediction), handling formula, XY, and recipe inputs uniformly.
Quick Reference
| Task | Function |
|---|---|
| Preprocess training data | mold(x, y) or mold(formula, data) |
| Preprocess prediction data | forge(new_data, blueprint) |
| Create model object | new_model(..., blueprint, class) |
| XY blueprint | default_xy_blueprint(intercept = TRUE) |
| Formula blueprint | default_formula_blueprint(intercept = TRUE) |
| Recipe blueprint | default_recipe_blueprint(intercept = TRUE) |
| Format numeric predictions | spruce_numeric(pred) |
| Format class predictions | spruce_class(pred) |
| Format probability predictions | spruce_prob(pred) |
| Validate univariate outcome | validate_outcomes_are_univariate(outcomes) |
| Validate prediction size | validate_prediction_size(pred, new_data) |
Package Architecture
Stage 1: Model Fitting
User → simple_lm() methods → bridge → implementation → constructor
(formula/xy/recipe) ↓ ↓ ↓
mold() lm.fit() new_model()
Stage 2: Model Prediction
User → predict.simple_lm() → bridge → implementation
↓ ↓ ↓
forge() switch() predict_*_numeric()
Model Constructor
Create objects of your model class. Name: new_<model_class>().
new_simple_lm <- function(coefs, coef_names, blueprint) {
if (!is.numeric(coefs)) {
stop("`coefs` should be a numeric vector.", call. = FALSE)
}
if (!is.character(coef_names)) {
stop("`coef_names` should be a character vector.", call. = FALSE)
}
new_model(
coefs = coefs,
coef_names = coef_names,
blueprint = blueprint,
class = "simple_lm"
)
}
Implementation Function
Core algorithm. Name: <model_class>_impl(). Returns named list of model elements.
simple_lm_impl <- function(predictors, outcomes) {
lm_fit <- lm.fit(predictors, outcomes)
coefs <- lm_fit$coefficients
list(
coefs = unname(coefs),
coef_names = names(coefs)
)
}
Bridge Function
Connects user-facing methods to implementation. Converts mold() output to implementation format.
simple_lm_bridge <- function(processed) {
validate_outcomes_are_univariate(processed$outcomes)
predictors <- as.matrix(processed$predictors)
outcomes <- processed$outcomes[[1]]
fit <- simple_lm_impl(predictors, outcomes)
new_simple_lm(
coefs = fit$coefs,
coef_names = fit$coef_names,
blueprint = processed$blueprint
)
}
User-Facing Fitting Function
Generic with methods for each interface. Each method calls mold() then the bridge.
simple_lm <- function(x, ...) {
UseMethod("simple_lm")
}
simple_lm.default <- function(x, ...) {
stop("`simple_lm()` is not defined for a '", class(x)[1], "'.", call. = FALSE)
}
simple_lm.data.frame <- function(x, y, intercept = TRUE, ...) {
blueprint <- default_xy_blueprint(intercept = intercept)
processed <- mold(x, y, blueprint = blueprint)
simple_lm_bridge(processed)
}
simple_lm.matrix <- function(x, y, intercept = TRUE, ...) {
blueprint <- default_xy_blueprint(intercept = intercept)
processed <- mold(x, y, blueprint = blueprint)
simple_lm_bridge(processed)
}
simple_lm.formula <- function(formula, data, intercept = TRUE, ...) {
blueprint <- default_formula_blueprint(intercept = intercept)
processed <- mold(formula, data, blueprint = blueprint)
simple_lm_bridge(processed)
}
simple_lm.recipe <- function(x, data, intercept = TRUE, ...) {
blueprint <- default_recipe_blueprint(intercept = intercept)
processed <- mold(x, data, blueprint = blueprint)
simple_lm_bridge(processed)
}
Prediction Implementation
One function per prediction type. Use spruce_*() for standardized output.
predict_simple_lm_numeric <- function(object, predictors) {
coefs <- object$coefs
pred <- as.vector(predictors %*% coefs)
spruce_numeric(pred) # Returns tibble with .pred column
}
Prediction Bridge
Converts forge() output and switches on type.
predict_simple_lm_bridge <- function(type, object, predictors) {
type <- rlang::arg_match(type, "numeric")
predictors <- as.matrix(predictors)
switch(
type,
numeric = predict_simple_lm_numeric(object, predictors)
)
}
User-Facing Predict Method
Call forge() with blueprint, then bridge, then validate.
predict.simple_lm <- function(object, new_data, type = "numeric", ...) {
processed <- forge(new_data, object$blueprint)
out <- predict_simple_lm_bridge(type, object, processed$predictors)
validate_prediction_size(out, new_data)
out
}
mold() Details
Returns: predictors (tibble), outcomes (tibble), extras, blueprint.
Blueprint Options
| Blueprint | Key Options |
|---|---|
default_xy_blueprint() | intercept |
default_formula_blueprint() | intercept, indicators ("traditional", "none", "one_hot") |
default_recipe_blueprint() | intercept |
Formula Special Behaviors
- No intercept by default (unlike base R)
indicators = "none"keeps factors unexpanded- Multivariate outcomes:
y1 + y2 ~ x1 + x2(notcbind())
forge() Validation
Automatically validates new data matches training data:
- Column names must match
- Column types must be compatible
- Factor levels must be subset of training levels
- Lossy conversions emit warnings (novel levels → NA)
# Missing column → error
# Wrong type (double for factor) → error
# Character for factor → silent conversion
# Novel factor level → warning + NA
Spruce Functions
Standardize prediction output to tidymodels conventions:
| Function | Output Column |
|---|---|
spruce_numeric(pred) | .pred |
spruce_class(pred) | .pred_class |
spruce_prob(pred_matrix) | .pred_{class_name} |
Validation Functions
| Function | Checks |
|---|---|
validate_outcomes_are_univariate() | Single outcome column |
validate_prediction_size() | Output rows == input rows |
validate_outcomes_are_numeric() | Numeric outcomes |
validate_predictors_are_numeric() | Numeric predictors |
See Also
- designing-tidy-r-functions: Function API design
- r-metaprogramming: Expression manipulation (if customizing blueprints)
- testing-r-packages: Testing patterns
Vignettes
Access detailed documentation via R:
# Open vignette in browser
RShowDoc("mold", package = "hardhat") # Molding data for modeling
RShowDoc("forge", package = "hardhat") # Forging data for predictions
RShowDoc("package", package = "hardhat") # Creating modeling packages
# Or browse all vignettes
browseVignettes("hardhat")
External Resources
R Metaprogramming with rlang
Metaprogramming is the ability to defuse, create, and inject R expressions. The core pattern is defuse-and-inject: capture code as data, optionally transform it, then inject it into another context for evaluation.
Quick Reference
| Task | Function/Operator |
|---|---|
| Defuse your own expression | expr(x + 1) |
| Defuse user's single argument | enquo(arg) |
Defuse user's ... arguments | enquos(...) |
| Inject single expression | !! or {{ |
| Splice list of expressions | !!! |
| Get expression from quosure | quo_get_expr(q) |
| Get environment from quosure | quo_get_env(q) |
| Build symbol from string | sym("name") |
| Build symbol with .data pronoun | data_sym("name") |
| Build symbols from vector | syms(names) / data_syms(names) |
| Auto-label expression | as_label(quo) |
| Format argument as string | englue("{{ x }}") |
| Interpolate name in dynamic dots | "{name}" := value |
| Interpolate argument in name | "{{ arg }}" := value |
Defusing Expressions
Defusing stops evaluation and returns the expression as a tree-like object (a "blueprint" for computation).
# Normal evaluation returns result
1 + 1
#> [1] 2
# Defusing returns the expression
expr(1 + 1)
#> 1 + 1
expr() vs enquo()
| Function | Defuses | Returns | Use When |
|---|---|---|---|
expr() | Your own code | Expression | Building expressions locally |
enquo() | User's argument | Quosure | Forwarding function arguments |
enquos() | User's ... | List of quosures | Forwarding multiple arguments |
# Defuse your own expression
my_expr <- expr(mean(x, na.rm = TRUE))
# Defuse user's function argument (returns quosure)
my_function <- function(var) {
enquo(var)
}
my_function(cyl + am)
#> <quosure>
#> expr: ^cyl + am
#> env: global
enquos() with .named
Auto-label unnamed arguments:
g <- function(...) {
vars <- enquos(..., .named = TRUE)
names(vars)
}
g(cyl, 1 + 1)
#> [1] "cyl" "1 + 1"
g(foo = cyl, bar = 1 + 1)
#> [1] "foo" "bar"
Types of Defused Expressions
- Calls:
f(x, y),1 + 1- function invocations - Symbols:
x,df- named object references - Constants:
1,"text",NULL- literal values
Quosures
A quosure wraps an expression with its original environment. This is critical for correct evaluation when expressions travel across function and package boundaries.
Why Environments Matter
# In package A
my_function <- function(data, var) {
# 'var' was defined in the user's environment
# The quosure tracks that environment
var <- enquo(var)
# When passed to package B's function, the quosure
# ensures symbols resolve in the correct environment
pkg_b_function(data, !!var)
}
Without environment tracking, symbols might resolve to wrong objects when code crosses package boundaries.
When You Need Quosures
| Situation | Use Quosure? |
|---|---|
| Defusing function arguments | Yes - use enquo() |
| Building local expressions | No - use expr() |
| Cross-package composition | Yes - environments matter |
| Simple local evaluation | No - expr() + eval() suffices |
Quosure Operations
q <- enquo(x + 1)
quo_get_expr(q) # Extract expression: x + 1
quo_get_env(q) # Extract environment
# Create quosure manually
new_quosure(expr(x + 1), env = global_env())
# Convert expression to quosure
as_quosure(expr(x + 1), env = global_env())
Injection Operators
Injection inserts defused expressions back into code before evaluation.
{{ (Embrace)
Defuses and injects in one step. Equivalent to !!enquo(arg):
# These are equivalent:
my_summarise <- function(data, var) {
data |> dplyr::summarise({{ var }})
}
my_summarise <- function(data, var) {
data |> dplyr::summarise(!!enquo(var))
}
Use {{ when you simply need to forward an argument. Use enquo() + !! when you need to inspect or transform the expression first.
!! (Bang-Bang)
Injects a single expression:
var <- expr(cyl)
mtcars |> dplyr::summarise(mean(!!var))
#> Equivalent to: summarise(mean(cyl))
# Inject a value to avoid name collisions
x <- 100
df |> dplyr::mutate(x = x / !!x)
#> Uses column x divided by env value 100
!!! (Splice)
Injects each element of a list as separate arguments:
vars <- exprs(cyl, am, vs)
mtcars |> dplyr::select(!!!vars)
#> Equivalent to: select(cyl, am, vs)
# With enquos()
my_group_by <- function(.data, ...) {
.data |> dplyr::group_by(!!!enquos(...))
}
Where Operators Work
- Data-masked arguments: Implicitly enabled (dplyr, ggplot2, etc.)
- inject(): Explicitly enables operators in any context
- Dynamic dots:
!!!and{name}work in functions usinglist2()
# Enable injection in base functions
inject(
with(mtcars, mean(!!sym("cyl")))
)
Building Expressions from Data
sym() and syms()
Convert strings to symbols:
var <- "cyl"
sym(var)
#> cyl
vars <- c("cyl", "am")
syms(vars)
#> [[1]]
#> cyl
#> [[2]]
#> am
data_sym() and data_syms()
Create .data$col expressions (safer in tidy eval, avoids collisions):
data_sym("cyl")
#> .data$cyl
data_syms(c("cyl", "am"))
#> [[1]]
#> .data$cyl
#> [[2]]
#> .data$am
Use sym() for base R functions; use data_sym() for tidy eval functions.
Building Calls
# With call()
call("mean", sym("x"), na.rm = TRUE)
#> mean(x, na.rm = TRUE)
# With expr() and injection
var <- sym("x")
expr(mean(!!var, na.rm = TRUE))
#> mean(x, na.rm = TRUE)
Name Interpolation (Glue Operators)
In dynamic dots, use glue syntax for names.
{ for Variable Values
name <- "foo"
tibble::tibble("{name}" := 1:3)
#> # A tibble: 3 x 1
#> foo
#> <int>
#> 1 1
#> 2 2
#> 3 3
tibble::tibble("prefix_{name}" := 1:3)
#> Column named: prefix_foo
{{ for Argument Labels
my_mutate <- function(data, var) {
data |> dplyr::mutate("mean_{{ var }}" := mean({{ var }}))
}
mtcars |> my_mutate(cyl)
#> Creates column: mean_cyl
englue() for String Formatting
my_function <- function(var) {
englue("Column: {{ var }}")
}
my_function(some_column)
#> [1] "Column: some_column"
Advanced: Manual Expression Transformation
When you need to modify expressions before injection:
my_mean <- function(data, var) {
# 1. Defuse
var <- enquo(var)
# 2. Transform: wrap in mean()
wrapped <- expr(mean(!!var, na.rm = TRUE))
# 3. Inject
data |> dplyr::summarise(mean = !!wrapped)
}
For multiple arguments:
my_mean <- function(.data, ...) {
vars <- enquos(..., .named = TRUE)
# Transform each expression
vars <- purrr::map(vars, ~ expr(mean(!!.x, na.rm = TRUE)))
.data |> dplyr::summarise(!!!vars)
}
Base R Equivalents
| rlang | Base R | Notes |
|---|---|---|
expr() | bquote() | bquote uses .() for injection |
enquo() | substitute() | substitute returns naked expr, not quosure |
enquos(...) | eval(substitute(alist(...))) | Workaround for dots |
!! | .() in bquote | Only inside bquote |
eval_tidy() | eval() | eval_tidy supports .data/.env pronouns |
Pitfalls
{{ on Non-Arguments
{{ should only wrap function arguments. On regular objects, it captures the value, not the expression:
# Correct: var is a function argument
my_fn <- function(var) {{ var }}
# Problematic: x is not an argument
x <- 1
{{ x }} # Returns 1, not the expression
Operators Out of Context
Outside tidy eval/inject contexts, operators have different meanings:
| Operator | Intended | Outside Context |
|---|---|---|
{{ | Embrace | Double braces (returns value) |
!! | Inject | Double negation (logical) |
!!! | Splice | Triple negation (logical) |
These fail silently. See the tidy-evaluation skill for details on proper usage contexts.
See Also
- tidy-evaluation: Programming patterns for data-masked functions
- designing-tidy-r-functions: Function API design principles
- rlang-conditions: Error handling with rlang
Reference Files
- topic-quosure.md - Complete quosure reference
- topic-metaprogramming.md - Advanced transformation patterns
- topic-multiple-columns.md - Multiple columns patterns
Vignettes
Access detailed rlang documentation via R:
# Defusing expressions
vignette("topic-defuse", package = "rlang")
# Injection operators
vignette("topic-inject", package = "rlang")
# Or browse all vignettes
browseVignettes("rlang")
R Language Server Protocol Integration
The R languageserver provides code intelligence for R files through the LSP tool. Use these capabilities as a "sensor array" for understanding R codebases—retrieving documentation, navigating definitions, and analyzing call graphs without reading entire files.
Reach for the LSP before grep
For any question about where a symbol is defined or used—call sites, callers, definitions, call hierarchies—use the LSP operations below, not Grep. This is the default, not an optimization: text search silently returns wrong answers on real codebases. Grep matches a function's name inside comments, #' roxygen lines, string literals, and unrelated identifiers, and it cannot tell a definition from a call or follow scoping. findReferences / incomingCalls resolve the symbol semantically instead.
Concretely, searching for ProcessData with Grep also matches the name inside a test_that("...") description string and the roxygen comment above its definition; findReferences reports only the real call sites. On a small file the difference may not change your answer, but on a package with reused names, S3 methods, and shadowed variables it does.
Grep remains the right tool for free-text pattern searches—a TODO, a literal string, a regex across non-R files. Use it for text, not for symbols.
Available Operations
| Operation | Purpose | Primary Use Case |
|---|---|---|
hover | Get documentation | Understanding function contracts |
goToDefinition | Jump to definition | Navigating to function source |
findReferences | Find all usages | Impact analysis before changes |
documentSymbol | List file symbols | File structure overview |
workspaceSymbol | Search all symbols | Finding functions across project |
incomingCalls | What calls this? | Understanding dependencies |
outgoingCalls | What does this call? | Understanding execution flow |
prepareCallHierarchy | Initialize call tree | Preparing for call analysis |
Not Supported
goToImplementation is not implemented by R languageserver. Use goToDefinition instead.
Critical Concept: Character Positioning
The most common cause of failed LSP operations is incorrect character positioning.
All operations require precise cursor placement ON the symbol:
# Line 15: result <- MyFunction(data, config)
# ^ ^ ^
# col 3 col 14 col 25
- Position on
result(col 3-8): References to this variable - Position on
MyFunction(col 14-23): Definition/references of the function - Position on
data(col 25-28): References to the argument
When an operation returns "no definition found" or "no hover information," adjust the character position before assuming the symbol isn't indexed.
Core Workflows
1. File Structure Before Reading
Instead of reading a 500-line file to find one function, use documentSymbol first:
LSP documentSymbol on large_file.R
→ Returns: FunctionA (Line 45), FunctionB (Line 120), FunctionC (Line 280)
→ Then: Read file with offset=118, limit=50 to see just FunctionB
This retrieves the file's "sitemap" and enables targeted reading.
Note: R languageserver also indexes comment-based section markers (# ====, # ----, # ---- Section Name ----). These appear in documentSymbol output, useful for navigating large files organized with sections.
2. Understanding External Functions
When encountering an unfamiliar function from an external package, use hover:
LSP hover on purrr::map_lgl at line 48, character 20
→ Returns: Full documentation with description, parameters, return value, examples
This retrieves package documentation without web searches or leaving the editor. Hover works for:
- Base R functions (
summary,grep,setdiff) - Tidyverse and other CRAN packages
- Locally defined functions (when called, not at definition site)
- Unexported functions accessed via
:::(shows signature only)
3. Impact Analysis Before Modifying
Before changing a function's signature or behavior, use incomingCalls to find all callers:
LSP incomingCalls on ProcessData at line 50, character 1
→ Returns:
- targets/pipeline.R: run_analysis (Line 30) [calls at: 45:5]
- R/helpers.R: batch_process (Line 80) [calls at: 92:12]
- tests/test-process.R: test cases (Lines 15, 28, 41)
This reveals the blast radius of any change. The output includes:
- File paths of callers
- Function/target names containing the calls
- Exact line and column of each call site
4. Understanding Execution Flow
To understand what a function depends on, use outgoingCalls:
LSP outgoingCalls on FitModel at line 100, character 1
→ Returns:
- validate_input (local) [called from: 105:3]
- checkmate::assert_class [called from: 106:3, 107:3]
- recipes::prep [called from: 115:12]
- parsnip::fit [called from: 120:12]
This maps the function's dependencies, showing:
- Which functions are called
- Whether they're local or from packages
- Every call site within the function
5. Cross-File Navigation
To find where a symbol is used across the entire project, use findReferences:
LSP findReferences on helper_function at line 25, character 1
→ Returns:
- R/helpers.R: Line 25:1 (definition)
- R/main.R: Line 45:12, Line 78:8
- tests/test-helpers.R: Line 12:5, Line 30:5
References work across:
- Package R/ source files
- Test files
- targets/ pipeline definitions
- Any .R file in the workspace
6. Finding Functions Project-Wide
To locate a function without knowing which file contains it, use workspaceSymbol:
LSP workspaceSymbol (from any R file)
→ Returns all indexed symbols:
- R/data.R: ProcessData (Function) - Line 15
- R/models.R: FitModel (Function) - Line 42
- R/utils.R: validate_input (Function) - Line 8
- targets/pipeline.R: data_tar (Field) - Line 5
Use this sparingly. The R languageserver ignores the query string and returns every indexed symbol in the workspace — on a large package that is one enormous dump of output for a single lookup. Prefer, in order:
documentSymbolon the file you suspect (a per-file sitemap, always cheap)goToDefinitionfrom a call site you already know aboutworkspaceSymbolonly on small projects, or when you genuinely have no lead
If you need a name search on a large package, a targeted Grep for the definition pattern (e.g. FitModel <- function) costs less context than an unfiltered symbol dump.
Behavior Notes
Installed vs. Non-Installed Packages
The LSP reads source from the workspace, not from installed packages. Both installed local packages and non-installed packages in the workspace work identically for all operations.
External Package Definitions
When goToDefinition resolves to an external package (CRAN, tidyverse, etc.), the definition points to a temporary file:
/var/folders/.../RtmpXXXXX/function_name.R
This is extracted source code from the installed package. The content is readable and accurate but the path is ephemeral.
Diagnostics: Correctness-Only by Design
Editing or accessing R files makes the languageserver publish lintr diagnostics, which appear in tool output as <new-diagnostics> blocks. This cannot be explicitly requested—diagnostics arrive as a push channel after edits and indexing.
When the project has no .lintr/.lintr.R of its own, the plugin applies a correctness-only lint profile: syntax errors plus linters that catch real bugs (object_usage_linter, missing_package_linter, equals_na_linter, missing_argument_linter, T_and_F_symbol_linter, and similar). Treat every diagnostic you receive as a genuine problem worth fixing.
What you will NOT see, and must not chase:
- No style lints (line length, spacing, indentation, implicit integers). The
airformatting hook rewrites every file after each Write/Edit — style is handled for you, for free. Never spend edits on formatting. - If the project ships its own
.lintr, that config always wins and you see whatever the project's CI sees, style lints included. Even then, formatting-class complaints usually resolve themselves at the next edit via the hook.
Stale Positions After the Format Hook
The air hook reformats the file on disk after your edit, but that rewrite is not replayed to the language server — the server's view of the file lags disk by exactly one formatting pass, until your next edit resyncs it. If the reformat changed line counts, LSP answers (definition/reference/diagnostic line numbers) can be off for positions below your edit.
Rule of thumb: after an edit that the hook may have reformatted, re-Read the file before trusting LSP line numbers in that file. Any subsequent edit heals the skew automatically.
Workspace Indexing
Some operations require files to be "seen" by the LSP before they're fully indexed. If findReferences or workspaceSymbol returns incomplete results, access the relevant files first (via any LSP operation) to trigger indexing.
When to Use LSP vs Other Tools
| Task | Preferred Approach |
|---|---|
| Find function definition (external package) | goToDefinition |
| Find function definition (local) | goToDefinition; Read only if you already know the file and line |
| Get function documentation | hover |
| List functions in a file | documentSymbol |
| Find all usages of a function | findReferences |
| Search for a function by name | documentSymbol on likely files first; workspaceSymbol only on small projects (it dumps every symbol, unfiltered) |
| Understand what calls a function | incomingCalls |
| Understand what a function calls | outgoingCalls |
| Read function implementation | Read with offset/limit |
| Search for free-text patterns (not a symbol) | Grep |
Quick Reference
Operation Parameters
All operations require:
filePath: Absolute path to an R fileline: 1-based line numbercharacter: 1-based character offset
Successful Output Patterns
hover: Returns markdown-formatted documentation with signature, description, parameters, and examples.
goToDefinition: Returns Defined in path/to/file.R:line:column
findReferences: Returns Found N references across M files: followed by file paths and line numbers.
documentSymbol: Returns Found N symbols in workspace: followed by function names, types, and line numbers.
incomingCalls/outgoingCalls: Returns Found N calls: with caller/callee information and call site locations.
Failure Patterns
- "No definition found" → Check character position; ensure cursor is ON the symbol
- "No hover information" → Symbol may be at definition site (hover works on calls, not definitions for local functions)
- "No references found" → File may not be indexed; try accessing it first
- "LSP request failed" → Operation not supported (e.g.,
goToImplementation)
Condition Handling in R Packages
When to Use What
| Task | Use |
|---|---|
| Throw formatted error | cli_abort() with message and bullets |
| Throw formatted warning | cli_warn() with message and bullets |
| Display informative message | cli_inform() with message and bullets |
| Show correct function in error | call = caller_env() argument |
| Get argument name dynamically | arg = caller_arg(x) in input checkers |
| Catch and rethrow with context | try_fetch() with parent = cnd |
| Take ownership of low-level error | try_fetch() with parent = NA |
| Test error messages | expect_snapshot(error = TRUE, ...) |
CLI Conditions Essentials
Use cli_abort(), cli_warn(), and cli_inform() instead of base R's stop(), warning(), and message() for formatted condition messages.
Basic Usage
# Simple error
cli_abort("Column {.field name} is required")
# Simple warning
cli_warn("Column {.field {col}} has missing values")
# Simple message
cli_inform("Processing {n} file{?s}")
Structured Messages with Bullets
Use named character vectors for multi-part messages:
cli_abort(c(
"File not found",
"x" = "Cannot read {.file {path}}",
"i" = "Check that the file exists"
))
Bullet types:
"x"- Error/problem (red X)"!"- Warning (yellow !)"i"- Information (blue i)"v"- Success (green checkmark)"*"- Bullet point">"- Arrow/pointer
Essential Inline Markup
Format values in condition messages for clarity:
# Arguments
cli_abort("{.arg x} must be numeric")
# Files and paths
cli_abort("Cannot find {.file {path}}")
# Values
cli_abort("Expected {.val TRUE}, got {.val {x}}")
# Classes/types
cli_abort("Expected numeric, got {.cls {class(x)}}")
# Code
cli_abort("Use {.code na.rm = TRUE} to ignore missing values
")
# Function names
cli_abort("See {.fn mypackage::helper} for details")
Pluralization
Use {?} for automatic singular/plural handling:
cli_abort("Found {n} error{?s}")
#> Found 1 error
#> Found 3 errors
cli_abort("Found {n} director{?y/ies}")
#> Found 1 directory
#> Found 5 directories
Error Call Context
By default, abort() and cli_abort() show the function where they are called. When using error helpers, pass call = caller_env() to show the user's function instead.
The Problem
# Error helper without call context
stop_my_class <- function(message) {
abort(message, class = "my_class")
}
my_function <- function(x) {
stop_my_class("Something went wrong")
}
my_function("test")
#> Error in `stop_my_class()`:
#> ! Something went wrong
The error shows stop_my_class() but users called my_function().
The Solution
stop_my_class <- function(message, call = caller_env()) {
abort(message, class = "my_class", call = call)
}
my_function <- function(x) {
stop_my_class("Something went wrong")
}
my_function("test")
#> Error in `my_function()`:
#> ! Something went wrong
Now the error correctly shows my_function().
Pattern: Abort Wrapper
stop_my_class <- function(message, call = caller_env()) {
abort(message, class = "my_class", call = call)
}
Input Checkers
Input checkers validate function arguments. Use caller_arg() to get the argument name dynamically and caller_env() for proper error context.
Basic Input Checker
check_string <- function(x,
arg = caller_arg(x),
call = caller_env()) {
if (!is_string(x)) {
cli_abort("{.arg {arg}} must be a string.", call = call)
}
}
Using the Checker
my_function <- function(my_arg) {
check_string(my_arg)
# ... rest of function
}
my_function(NA)
#> Error in `my_function()`:
#> ! `my_arg` must be a string.
The error shows:
- The correct function (
my_function, notcheck_string) - The correct argument name (
my_arg, notx)
Pattern: Complete Input Checker
check_scalar_numeric <- function(x,
arg = caller_arg(x),
call = caller_env()) {
if (!is.numeric(x) || length(x) != 1) {
cli_abort(c(
"{.arg {arg}} must be a single number",
"x" = "You supplied {.cls {class(x)}} of length {length(x)}"
), call = call)
}
}
Built-in Checkers from rlang
rlang provides check_required() for mandatory arguments:
my_function <- function(data) {
check_required(data)
# ... rest of function
}
my_function()
#> Error in `my_function()`:
#> ! `data` is absent but must be supplied.
Error Chaining
Error chaining adds context when catching and rethrowing errors. Use try_fetch() to catch errors and parent to chain them.
Basic Error Chaining
with_chained_errors <- function(expr, call = caller_env()) {
try_fetch(
expr,
error = function(cnd) {
abort("Problem during step.", parent = cnd, call = call)
}
)
}
my_verb <- function(expr) {
with_chained_errors(expr)
}
my_verb(1 + "a")
#> Error in `my_verb()`:
#> ! Problem during step.
#> Caused by error in `1 + "a"`:
#> ! non-numeric argument to binary operator
Why try_fetch() Over tryCatch()
- Preserves full backtrace context for debugging
- Allows
options(error = recover)to work - Catches stack overflow errors (R >= 4.2.0)
Taking Ownership of Errors
Use parent = NA to completely replace a low-level error:
with_user_friendly_errors <- function(expr, call = caller_env()) {
try_fetch(
expr,
vctrs_error_scalar_type = function(cnd) {
abort(
"Must supply a vector.",
parent = NA,
error = cnd, # Store original for debugging
call = call
)
}
)
}
For advanced error chaining patterns: See references/error-chaining.md for iteration context, modifying error calls, and case studies.
Testing Error Conditions
Use testthat snapshot tests to verify error messages.
Basic Snapshot Test
test_that("validation errors are clear", {
expect_snapshot(error = TRUE, {
my_function(NULL)
})
})
This creates a snapshot file recording the exact error output.
Testing Multiple Cases
test_that("input validation catches bad inputs", {
expect_snapshot(error = TRUE, {
check_string(123)
check_string(NA)
check_string(c("a", "b"))
})
})
Enabling rlang Error Display
To see the call field in error snapshots, depend on rlang >= 1.0.0 in your package. With testthat >= 3.1.2, this enables the enhanced error display automatically.
Testing Error Classes
test_that("errors have correct class", {
expect_error(
validate_input(NULL),
class = "validation_error"
)
})
Resources
rlang Documentation
cli Documentation
Style Guide
Reference Files
- references/error-chaining.md - Advanced error chaining patterns
- references/customisation.md - Condition appearance customization
Complex targets Pipelines
Branching creates multiple targets from a single definition. Choose your approach based on when iterations are known and what naming you need.
Quick Reference
| Task | Approach | Key Function/Pattern |
|---|---|---|
| Variants from known parameters | Static | tarchetypes::tar_map() |
| Aggregate static variants | Static | tarchetypes::tar_combine() |
| Runtime-determined iterations | Dynamic | pattern = map(x) |
| All combinations (cartesian) | Dynamic | pattern = cross(x, y) |
| Batched simulation reps | Dynamic | tarchetypes::tar_rep() |
| Static variants + batched reps | Hybrid | tarchetypes::tar_map_rep() |
| Branch over row groups | Dynamic | tarchetypes::tar_group_by() |
| Reusable multi-target pattern | Factory | Custom function + tar_target_raw() |
Decision Tree
Need multiple similar targets?
│
├─ NO ──► Single target, or consider a target factory
│ for reusable patterns
│
└─ YES ─► Iterations known before tar_make()?
│
├─ NO ──► DYNAMIC BRANCHING
│ pattern = map() / cross()
│ → topic-dynamic-branching.md
│
└─ YES ─► Need friendly target names in DAG?
│
├─ YES ──► STATIC BRANCHING
│ tarchetypes::tar_map()
│ → topic-static-branching.md
│
└─ NO ───► Either works; prefer dynamic
for simplicity at scale
Additional decisions:
Static variants + many replications?
└─► HYBRID: tarchetypes::tar_map_rep()
→ topic-hybrid-branching.md
Encapsulating a reusable multi-target pattern?
└─► TARGET FACTORY: tar_target_raw()
→ topic-target-factories.md
Approach Comparison
| Aspect | Static | Dynamic | Hybrid |
|---|---|---|---|
| When defined | Before tar_make() | During tar_make() | Both |
| Target names | Friendly (analysis_bayesian) | Hashed (analysis_3a7f2b) | Mixed |
| Scale | <1000 targets | 100k+ targets | Moderate |
| Validation | Full tar_manifest() | Must run to see branches | Partial |
| Use case | Method comparison | Simulations, file processing | Methods x replications |
Static Branching Overview
Use tarchetypes::tar_map() when iterations are known at define-time and you want readable target names.
values <- tibble::tibble(
method = rlang::syms(c("analyze_bayesian", "analyze_freq")),
method_name = c("bayesian", "freq")
)
tarchetypes::tar_map(
values = values,
names = "method_name",
targets::tar_target(result, method(data)),
targets::tar_target(summary, summarize_result(result))
)
# Creates: result_bayesian, result_freq, summary_bayesian, summary_freq
Aggregate with tarchetypes::tar_combine():
mapped <- tarchetypes::tar_map(
unlist = FALSE,
values = values,
targets::tar_target(result, method(data))
)
tarchetypes::tar_combine(
all_results,
mapped[["result"]],
command = dplyr::bind_rows(!!!.x, .id = "method")
)
Key points:
- Function names must be symbols: use
rlang::syms(), not strings - Use
unlist = FALSEwhen you needtar_combine()afterward !!!.xsplices the list of upstream results into the command
See topic-static-branching.md for details on tar_eval(), tar_sub(), and complex value construction.
Dynamic Branching Overview
Use the pattern argument when branch count depends on data or you need massive scale.
list(
targets::tar_target(datasets, c("trial_A", "trial_B", "trial_C")),
targets::tar_target(
analysis,
analyze_data(datasets),
pattern = map(datasets)
)
)
Pattern types:
map(x, y)- parallel iteration (zip)cross(x, y)- cartesian productslice(x, index = c(1, 3))- specific elementshead(x, n = 5)/tail()/sample()- subsets
Critical: Patterns reference target names, not R objects or expressions.
# WRONG: Can't reference external objects
my_vec <- 1:5
targets::tar_target(x, process(my_vec), pattern = map(my_vec))
# CORRECT: Reference upstream target by name
list(
targets::tar_target(params, 1:5),
targets::tar_target(result, process(params), pattern = map(params))
)
See topic-dynamic-branching.md for iteration modes, row grouping, and batching.
Hybrid Patterns Overview
Combine static branching (for methods/variants) with dynamic branching (for replications):
values <- tibble::tibble(
method = rlang::syms(c("method_a", "method_b")),
method_name = c("a", "b")
)
tarchetypes::tar_map_rep(
name = sim_result,
command = method(simulate_data()),
values = values,
names = "method_name",
batches = 10,
reps = 100
)
See topic-hybrid-branching.md for complete patterns.
Target Factories Overview
A target factory is a function that returns pre-configured target objects:
#' @export
analyze_dataset <- function(name, file_path) {
name <- targets::tar_deparse_language(substitute(name))
name_data <- paste0(name, "_data")
sym_data <- as.symbol(name_data)
command <- substitute(analyze(data), env = list(data = sym_data))
list(
targets::tar_target_raw(name_data, substitute(load_csv(file_path))),
targets::tar_target_raw(name, command)
)
}
See topic-target-factories.md for metaprogramming patterns and validation.
Debugging and Troubleshooting
Validation Commands
# Check target definitions before running
targets::tar_manifest()
targets::tar_manifest(fields = c("name", "command", "pattern"))
# Visualize DAG (slow with many targets)
targets::tar_visnetwork(targets_only = TRUE)
# Test pattern logic without running pipeline
targets::tar_pattern(
cross(method, map(dataset, seed)),
method = 3,
dataset = 5,
seed = 10
)
Common Errors
| Error | Cause | Fix |
|---|---|---|
| "Target 'x' not found" in pattern | Pattern references non-existent target | Check spelling; ensure upstream target exists |
| "object 'x' not found" in command | External object in pattern | Create upstream target; patterns reference target names only |
| Strings not callable | Using c("func_a", "func_b") | Use rlang::syms() for function names |
| Can't selectively combine | Missing unlist = FALSE | Add to tar_map() when using tar_combine() |
| Cryptic target names | Dynamic branching default | Add metadata to output or use static branching |
Identifying Failed Branches
# Check which targets have errors
targets::tar_meta() |>
dplyr::filter(error != "")
# Read specific branch by index
targets::tar_read(target_name, branches = 1)
# Inspect all branch metadata
targets::tar_branches(target_name)
Debugging Strategies
- Start with
tar_manifest()- verify target count and commands before running - Test with subset - use
pattern = head(x, n = 3)for initial runs - Include provenance - add parameter values to branch outputs for traceability
- Check upstream first - use
tar_read()on dependencies before investigating branching
Common Mistakes
| Mistake | Problem | Fix |
|---|---|---|
pattern = map(df$col) | Can't reference external objects | Create upstream target |
method = c("fn_a", "fn_b") | Strings aren't callable | rlang::syms(c("fn_a", "fn_b")) |
Manual lapply + aggregation | Reinventing batching | Use tar_rep() or tar_map_rep() |
tar_make() without validation | Errors discovered late | Always tar_manifest() first |
expand_grid() with syms() inside | syms() doesn't expand in grid | Apply syms() after grid creation |
See Also
- r-metaprogramming: Expression manipulation for target factories
- tidy-evaluation: Programming with data-masked functions
- targetopia-packages.md: Package development workflows
Reference Files
- topic-static-branching.md - Full static branching guide
- topic-dynamic-branching.md - Full dynamic branching guide
- topic-hybrid-branching.md - Dynamic within static patterns
- topic-target-factories.md - Custom factory functions
- references/tarchetypes-functions.md - Function reference
- references/pattern-composition.md - Pattern algebra
- references/targets-utilities.md - Package author utilities
- templates/static-branching.R - Static branching code template
- templates/target-factory.R - Target factory code template
- targetopia-packages.md - Targetopia package development guide
External Resources
Tidy Evaluation Programming Patterns
Data masking lets you refer to data frame columns as if they were regular objects. Programming with data-masked functions requires special patterns to pass column references through your functions.
Quick Reference
| Goal | Pattern |
|---|---|
| Forward single argument | {{ var }} |
Forward ... to data-mask | ... directly |
Forward ... to tidy-select (single arg) | c(...) |
| Use column name from string | .data[[var]] |
| Use column names from vector | across(all_of(vars)) |
| Disambiguate env-variable | .env$x |
| Disambiguate data-variable | .data$x |
| Bridge selection to data-mask | across({{ var }}) |
| Bridge names to data-mask | across(all_of(vars)) |
| Bridge data-mask to selection | transmute() then all_of() |
| Prevent double evaluation | Assign to column first |
What is Data Masking?
Data masking inserts a data frame at the bottom of the environment chain, giving columns precedence over user-defined variables:
# Without masking: must use $ notation
mean(mtcars$cyl + mtcars$am)
# With masking: columns are directly accessible
with(mtcars, mean(cyl + am))
dplyr::summarise(mtcars, mean(cyl + am))
Why Injection is Needed
Data-masking functions defuse their arguments. When you wrap them, you must inject the user's expression:
# Without injection: summarise sees literal "var1 + var2"
my_mean <- function(data, var1, var2) {
dplyr::summarise(data, mean(var1 + var2)) # Error!
}
# With injection: summarise sees "cyl + am"
my_mean <- function(data, var1, var2) {
dplyr::summarise(data, mean({{ var1 }} + {{ var2 }}))
}
Argument Behaviors
| Behavior | Example Functions | Key Features |
|---|---|---|
| Data-masked | mutate(), summarise(), filter() | Column refs, .data/.env, {{, !! |
| Tidy-select | select(), pivot_longer(cols=) | Helpers (starts_with), c(), :, {{ |
| Dynamic dots | list2(), tibble() | !!! splice, {name} interpolation |
Documenting Argument Behaviors
#' @param var <[`data-masked`][dplyr::dplyr_data_masking]> Column to summarize.
#' @param cols <[`tidy-select`][dplyr::dplyr_tidy_select]> Columns to pivot.
#' @param ... <[`dynamic-dots`][rlang::dyn-dots]> Name-value pairs.
Forwarding Patterns
Single Argument with {{}}
The embrace operator forwards an argument, inheriting behavior from the wrapped function:
# Forwarding to data-masked context
my_summarise <- function(data, var) {
data |> dplyr::summarise({{ var }})
}
mtcars |> my_summarise(mean(cyl))
# Forwarding to tidy-select context
my_pivot <- function(data, cols) {
data |> tidyr::pivot_longer(cols = {{ cols }})
}
mtcars |> my_pivot(starts_with("c"))
Multiple Arguments with ...
Pass ... directly to data-masked functions:
my_group_by <- function(.data, ...) {
.data |> dplyr::group_by(...)
}
mtcars |> my_group_by(cyl, am)
For tidy-select functions taking a single argument, wrap in c():
my_pivot <- function(.data, ...) {
.data |> tidyr::pivot_longer(c(...))
}
mtcars |> my_pivot(cyl, am, vs)
Names Patterns
Use strings or character vectors instead of expressions. Your function becomes "regular" with no data-masking complications.
.data[[var]] for Single Column
my_mean <- function(data, var) {
data |> dplyr::summarise(mean = mean(.data[[var]]))
}
my_mean(mtcars, "cyl")
# No masking surprises
am <- "cyl"
my_mean(mtcars, am) # Uses "cyl", not masked
all_of() for Character Vectors
vars <- c("cyl", "am")
mtcars |> tidyr::pivot_longer(all_of(vars))
mtcars |> dplyr::select(all_of(vars))
Loop Pattern
vars <- c("cyl", "am", "vs")
for (var in vars) {
result <- mtcars |>
dplyr::summarise(mean = mean(.data[[var]]))
print(result)
}
# Or with purrr
purrr::map(vars, ~ dplyr::summarise(mtcars, mean = mean(.data[[.x]])))
Bridge Patterns
Convert between argument behaviors when the wrapped function doesn't match your desired interface.
Selection to Data-Mask: across()
Give your function tidy-select behavior when wrapping a data-masked function:
my_group_by <- function(data, var) {
data |> dplyr::group_by(across({{ var }}))
}
# Now supports selection helpers:
mtcars |> my_group_by(starts_with("c"))
For ..., wrap in c():
my_group_by <- function(.data, ...) {
.data |> dplyr::group_by(across(c(...)))
}
Names to Data-Mask: across(all_of())
Accept character vectors for data-masked operations:
my_group_by <- function(data, vars) {
data |> dplyr::group_by(across(all_of(vars)))
}
my_group_by(mtcars, c("cyl", "am"))
Data-Mask to Selection: transmute() Bridge
Three-step pattern for data-masked input to tidy-select functions:
my_pivot_longer <- function(data, ...) {
# 1. Capture inputs in data-masked context, get names
inputs <- dplyr::transmute(data, ...)
names <- names(inputs)
# 2. Update data with the expressions
data <- dplyr::mutate(data, !!!inputs)
# 3. Pass names to tidy-select
tidyr::pivot_longer(data, cols = all_of(names))
}
mtcars |> my_pivot_longer(cyl, am_scaled = am * 100)
Transformation Patterns
Named Arguments: Code Around {{}}
Add code around embraced arguments:
my_mean <- function(data, var) {
data |> dplyr::summarise(mean = mean({{ var }}, na.rm = TRUE))
}
... Arguments: Use across()
Map an expression across multiple columns:
my_mean <- function(data, ...) {
data |> dplyr::summarise(
across(c(...), ~ mean(.x, na.rm = TRUE))
)
}
mtcars |> my_mean(cyl, disp, hp)
Filter with if_all() / if_any()
Combine logical conditions across columns:
filter_non_min <- function(.data, ...) {
.data |> dplyr::filter(
if_all(c(...), ~ .x != min(.x, na.rm = TRUE))
)
}
filter_any_max <- function(.data, ...) {
.data |> dplyr::filter(
if_any(c(...), ~ .x == max(.x, na.rm = TRUE))
)
}
Disambiguation: .data and .env Pronouns
Data masking can cause collisions when variable names exist in both the data and environment.
Column Collisions
x <- 100
df <- data.frame(x = 1:3, y = 4:6)
# Ambiguous: which x?
df |> dplyr::mutate(z = y / x)
#> Uses column x (data takes precedence)
# Explicit: use environment x
df |> dplyr::mutate(z = y / .env$x)
In Functions (Critical)
Always use .env for function parameters that might collide:
my_rescale <- function(data, var, factor = 10) {
# Safe even if data has a 'factor' column
data |> dplyr::mutate(
"{{ var }}" := {{ var }} / .env$factor
)
}
Full Disambiguation
df |> dplyr::mutate(
result = .data$y / .env$x
)
Pitfalls
Double Evaluation
Expressions injected multiple times execute multiple times:
# BAD: times100() runs twice
summarise_stats <- function(data, var) {
data |> dplyr::summarise(
mean = mean({{ var }}),
sd = sd({{ var }})
)
}
# If var = times100(cyl), function executes twice
# GOOD: Evaluate once, reference result
summarise_stats <- function(data, var) {
data |>
dplyr::transmute(var = {{ var }}) |>
dplyr::summarise(mean = mean(var), sd = sd(var))
}
Exception: Glue strings ("{{ var }}") don't suffer from double evaluation.
{{ Out of Context
Outside data-masking, {{ becomes literal double-braces and silently returns the value:
# In non-tidy-eval function:
f <- function(x) {{ x }}
f(1 + 1)
#> [1] 2 # No error, but not defuse-and-inject
!! and !!! Out of Context
Outside injection context, these become logical negation:
x <- TRUE
!!x # Double negation: TRUE
!!!x # Triple negation: FALSE
No error, just wrong semantics.
{{ on Non-Arguments
{{ should only wrap function arguments:
# Correct
my_fn <- function(arg) {
summarise(data, {{ arg }})
}
# Problematic: x is not a defused argument
x <- expr(cyl)
summarise(data, {{ x }}) # Captures x's VALUE, not expression
Tidy Selection vs Data Masking
Tidy selection is not data masking. It interprets expressions rather than masking environments, so there's no ambiguity:
data <- data.frame(x = 1, data = 2)
# Tidy selection: no collision
data |> dplyr::select(data:ncol(data))
#> Works correctly
# Data masking: potential collision
data |> dplyr::mutate(y = data + 1)
#> Uses column 'data', not the data frame
See Also
- r-metaprogramming: Defusing, quosures, expression building mechanics
- designing-tidy-r-functions: Function API design principles
- rlang-conditions: Error handling with rlang
Vignettes
Access detailed rlang documentation via R:
# Data masking concepts
vignette("data-mask", package = "rlang")
# Programming with data masking
vignette("data-mask-programming", package = "rlang")
# Or browse all vignettes
browseVignettes("rlang")
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:
prep()estimates parameters from training databake()applies the prepped recipe to new data
# 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:
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:
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 roleall_numeric_predictors(),all_nominal_predictors()- by type and rolehas_role(),has_type()- explicit queries
3. Model Specification (parsnip)
Define the model type, engine, and mode separately from fitting:
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:
wflow <- workflow() |>
add_recipe(rec_spec) |>
add_model(model_spec)
5. Evaluation (tune + yardstick)
Use resampling or validation sets to assess performance:
# 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:
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:
# 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:
# 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:
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 linksreferences/common-problems.md- Common pitfalls when working with tidymodels and how to avoid them
External Documentation
- tidymodels.org - Official documentation and tutorials
- recipes.tidymodels.org - Recipe step reference
- parsnip.tidymodels.org - Model specifications
Commands 1
Test the R Language Server Protocol (LSP) setup and diagnose issues.
Run the diagnostic harness: !"$CLAUDE_PLUGIN_ROOT"/scripts/lsp-test-harness.sh
Based on the results:
If all tests pass:
- Confirm LSP should be functional
- Suggest restarting Claude Code session if issues persist
- Check if .lsp.json settings are appropriate for the project
If tests fail:
For each failed test, explain:
- What the test checks
- Why it might have failed
- How to fix it
Common fixes:
languageserver not installed:
install.packages("languageserver")
lintr not installed (affects diagnostics):
install.packages("lintr")
R not in PATH:
- Check R installation
- Ensure R is accessible from terminal
- May need to add R to PATH in shell profile
air formatter not installed:
- Install from https://github.com/posit-dev/air
- Or use
cargo install air-rif Rust is available
LSP configuration issues:
- Check .lsp.json for valid JSON syntax
- Verify languageserver settings are correct
If any test failed, ask the user whether to attempt automatic fixes. Only if they confirm, run this with the Bash tool (it installs R packages from CRAN):
"$CLAUDE_PLUGIN_ROOT"/scripts/lsp-test-harness.sh --fix
After any fixes, suggest restarting Claude Code to reload the LSP.
Hooks 1
Sponsors
Details
- Marketplace
- jsperger/llm-r-skills
- Author
- jsperger
- Category
- Languages
- License
- MIT
- Keywords
- r, rlang, tidyverse, tidymodels, targets, ggplot2, programming