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

1
  • 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. Commented Jul 11, 2018 at 1:40

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

ah great, that's awesome! will keep that one around for sure

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.