Skip to content

Instantly share code, notes, and snippets.

@alekrutkowski
Last active August 28, 2024 08:09
Show Gist options
  • Save alekrutkowski/41a1e90accdee8097c7eab626b23e8ff to your computer and use it in GitHub Desktop.
Save alekrutkowski/41a1e90accdee8097c7eab626b23e8ff to your computer and use it in GitHub Desktop.
R function to avoid the repetitions in situations like `list(first = first, second = second, third = third)`
namedList <- function(...) {
# Capture the variable names as symbols
# and convert symbols to character names
var_names <- as.character(as.list(substitute(list(...)))[-1])
# Create a named list
stats::setNames(mget(var_names, envir = parent.frame()), var_names)
}
### Usage example
# first <- 1.3
# second <- 20L
# third <- "III"
#
# # Inspect the result
# str( namedList(first, second, third) )
#
# # List of 3
# # $ first : num 1.3
# # $ second: int 20
# # $ third : chr "III"
#
# # Compare to plain list()
# str( list(first, second, third) )
#
# # List of 3
# # $ : num 1.3
# # $ : int 20
# # $ : chr "III"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment