name_self: Construct a list that names itself

View source: R/metaprogramming.R

name_selfR Documentation

Construct a list that names itself

Description

Construct a list that names itself

Usage

name_self(list_expr, .fn = ~.x)

Arguments

list_expr

A expression using a call to list, c, or the like, where all arguments are name-value pairs and the expression evaluates to a list.

.fn

A function passed to purrr::imap_chr, called on the character vector returned after coercing the element symbols in list_expr to name. Defaults to the identity function.

Value

A named list

Note

Names of named elements are preserved.

Examples

name_self(c(min, mean, max))
name_self(c(min, mean, max), .fn = ~ toupper(.x))
name_self(c(min, mean, max), .fn = function(x, y) {
  paste0(x, y)
})
name_self(c(min, mean, custom_name = max))

# Helps when naming produced by from `across()`
suppressPackageStartupMessages(library(dplyr))

## With `name_self()`, columns are named after the functions
mtcars %>%
  group_by(cyl) %>%
  summarize(across(where(~ max(.x) > 100), name_self(list(min, mean, max))))

## More specifically, it allows `"{.fn"}` inside `.names` to reference the function names
mtcars %>%
  group_by(cyl) %>%
  summarize(across(disp, name_self(list(min, avg = mean, max)), .names = "{.col}.{toupper(.fn)}"))

## Without `name_self()`, column names are suffixed with position indices
mtcars %>%
  group_by(cyl) %>%
  summarize(across(where(~ max(.x) > 100), list(min, mean, max)))

yjunechoe/penngradlings documentation built on Sept. 6, 2024, 8:13 p.m.