1

I'm looking for a function that does the same as list, but puts the names of the input variables into the element names of the list:

a <- 2
b <- c("foo","bar")
betterlist(a,b)

[[a]]
[1] 2

[[b]]
[1] "foo" "bar"

In the output of list(a,b), the names "a" and "b" would not appear. Does it already exist in any package?

Horst Grünbusch
  • 276
  • 1
  • 17

2 Answers2

1

Here's one way using ... :

betterlist = function(...) {
  result <- list(...)
  resultnames <- lapply(substitute(list(...)), deparse)
  names(result) <- resultnames[-1]
  return(result)
}

This should actually be even easier as the R help states

The expression list(...) evaluates all such arguments and returns them in a named list [...]

but for me, list(...) gives me an unnamed list (hence the explicit naming in the function above).

laubbas
  • 186
  • 1
  • 5
0

First guess:

list(a = a, b = b)
Edward R. Mazurek
  • 2,107
  • 16
  • 29