/r-skills:designing-tidy-r-functionsfrom r-skills
Guides designing R function APIs with predictable naming, argument ordering, and pipe-friendly patterns. Use when writing or reviewing R package functions.
Ships in r-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
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.
| 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) |
# Good: imperative verbs
mutate()
filter()
summarize()
# Exception: noun-y builders
geom_point()
recipe()
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()
# Very frequent -> short
c(), n(), df
# Less frequent -> descriptive
create_bootstrap_samples()
validate_model_specification()
# 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)
# 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")
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
}
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)))
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
}
| 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 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
For modeling functions, predictions should return tibbles:
.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
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")
# 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
}
Functions that change global state should return previous values:
# Good: returns previous value for restoration
old <- options(digits = 3)
# ... do work ...
options(old) # restore
# 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))
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
}
}
# 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) {
# ...
}
When defaults matter, tell the user:
my_function <- function(x, tz = Sys.timezone()) {
if (missing(tz)) {
cli::cli_inform("Using timezone: {.val {tz}}")
}
# ...
}
# 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
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
# 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)
}
Always preserve matrix structure:
# Bad: may return vector
X[, 1]
# Good: always returns matrix
X[, 1, drop = FALSE]
When reviewing R function design:
... comes between required and optional argumentsarg_match() with enumerated defaultsdrop = FALSEWhat SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub jsperger/llm-r-skills --plugin r-skills9 skills in this plugin
/ggplot2Use when working with R ggplot2 package, especially ggplot2 4.0+ features. Covers S7 migration (@ property access), theme defaults with ink/paper/accent, element_geom(), from_theme(), theme shortcuts (theme_sub_*), palette themes, labels with dictionary/attributes, discrete scale improvements (palette, continuous.limits, minor_breaks, sec.axis), position aesthetics (nudge_x/nudge_y, order), facet_wrap dir/space/layout, boxplot/violin/label styling, stat_manual(), stat_connect(), coord reversal./hardhatUse when creating an R modeling package that needs standardized preprocessing for formula, data frame, matrix, and recipe interfaces. Covers: mold() for training data preprocessing, forge() for prediction data validation, blueprints, model constructors, spruce functions for output formatting.
/metaprogrammingUse when writing R code that manipulates expressions, builds code programmatically, or needs to understand rlang's defuse/inject mechanics. Covers: defusing with expr()/enquo()/enquos(), quosure environment tracking, injection with !!/!!!/{{, symbol construction with sym()/syms(). Does NOT cover: data-mask programming patterns (tidy-evaluation), error handling (rlang-conditions), function design (designing-tidy-r-functions).
/rlang-conditionsUse when developing R packages that need to handle errors, warnings, and conditions properly. Covers: (1) cli_abort/cli_warn/cli_inform for throwing conditions with formatting, (2) Error call context with caller_env() and caller_arg(), (3) Input validation helpers that report the right function, (4) Error chaining with try_fetch() and parent argument, (5) Testing error conditions with testthat snapshots.
/r-languageserverUse when navigating, reading, or refactoring R code: finding where an R function is defined or called, tracing call hierarchies, finding a function's callers before changing it (impact analysis), looking up a function's documentation, or interpreting the lint diagnostics that appear after editing R files. Prefer the LSP over text search for these — it resolves symbols semantically and avoids false matches in comments, strings, and docstrings.
/targets-pipelinesUse when writing complex targets pipelines with branching, batching, or custom target factories. Symptoms: multiple similar targets, parameter sweeps, method comparisons, simulation studies. Covers: static branching (tar_map/tar_combine), dynamic branching (pattern argument), hybrid patterns, custom target factories, pipeline debugging. Does NOT cover: basic targets usage, HPC deployment, package development workflows (see targetopia-packages.md).
Other plugins' skills for the same job