/r-skills:rlang-conditionsfrom r-skills
Uses rlang's cli_abort, cli_warn, cli_inform and try_fetch to throw, chain, and test error conditions in R package development.
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.
Read when SKILL.md points to them.
| 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, ...) |
Use cli_abort(), cli_warn(), and cli_inform() instead of base R's stop(), warning(), and message() for formatted condition messages.
# 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}")
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/pointerFormat 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")
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
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.
# 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().
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().
stop_my_class <- function(message, call = caller_env()) {
abort(message, class = "my_class", call = call)
}
Input checkers validate function arguments. Use caller_arg() to get the argument name dynamically and caller_env() for proper error context.
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)
}
}
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:
my_function, not check_string)my_arg, not x)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)
}
}
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 adds context when catching and rethrowing errors. Use try_fetch() to catch errors and parent to chain them.
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
options(error = recover) to workUse 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.
Use testthat snapshot tests to verify error messages.
test_that("validation errors are clear", {
expect_snapshot(error = TRUE, {
my_function(NULL)
})
})
This creates a snapshot file recording the exact error output.
test_that("input validation catches bad inputs", {
expect_snapshot(error = TRUE, {
check_string(123)
check_string(NA)
check_string(c("a", "b"))
})
})
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.
test_that("errors have correct class", {
expect_error(
validate_input(NULL),
class = "validation_error"
)
})
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
9 skills in this plugin
/designing-tidy-r-functionsUse when designing R function APIs, reviewing R code for design issues, writing functions for R packages, or evaluating argument ordering and naming decisions. Does NOT cover: style/linting, error handling (rlang-conditions), CLI output (r-lib:cli), testing (testing-r-packages), CRAN compliance (cran-extrachecks).
/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).
/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).
npx claudepluginhub jsperger/llm-r-skills --plugin r-skillsOther plugins' skills for the same job