Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

metaprogramming

БесплатноБез исполняемых скриптовНе проверен

Use when writing R code that manipulates expressions, builds code programmatically, or needs to understand rlang's defuse/inject mechanics. Covers: defusing…

jspergerот jsperger★ 17 звёзд на GitHub4 установки в других каталогах

Об этом скилле

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 using list2()
# Enable injection in base functions
inject(
  with(mtcars, mean(!!sym("cyl")))
)

Building Expressions from Data

sym() and syms()

Conver

Полный SKILL.md на GitHub

Установить metaprogramming в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

topic-metaprogramming.mdtopic-multiple-columns.mdtopic-quosure.md

FAQ

Что делает скилл metaprogramming?

Use 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).

Как установить скилл metaprogramming?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл metaprogramming запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить metaprogramming с