0

I am trying to take objects in my environment, and put them into a list or vector that is named with the names of the object. Here is an illustration:

a = 1
b = 2

desired <- c(a, b)
names(desired) <- c("a", "b")
desired
#> a b 
#> 1 2

My attempts have been variations of the following. I can see why this doesn't work (even if my terminology might not quite be right): it's pausing the evaluation after figuring out that ... is 1, 2. However, I want some way to get it to give a, b so that I can put the names on properly. I am open to any solutions, in base R, rlang or others.

name_list <- function(...){
  names <- enquote(list(...))
  values <- list(...)
  return(names)
}
print(name_list(a, b))
#> quote(list(1, 2))

Created on 2018-07-10 by the reprex package (v0.2.0).

Calum You
  • 14,687
  • 4
  • 23
  • 42
  • 1
    The `tibble::lst` function does this in a "tidyverse way": `tibble::lst(a, b)`. If you want to see how it does it, just type the name of the function without the parenthesis to see the source code: `tibble::lst`. – MrFlick Jul 11 '18 at 01:40

1 Answers1

3

You can use match.call to retrieve the names of the arguments being passed in

name_list <- function(...){
  vnames <- as.character(match.call())[-1]
  return(setNames(list(...), vnames))
}
a = 1; b=c(1,2)
name_list(a, b)
chinsoon12
  • 25,005
  • 4
  • 25
  • 35