20

I've looked extensively for a solution for this very simple task and though I have a solution, it seems like there must be a better way. The task is to create a list from a set of variables, using the variable names as names for each element in the list, e.g.:

a <- 2
b <- 'foo'
c <- 1:4

My current solution:

named.list <- function(...) { 
    l <- list(...)
    names(l) <- sapply(substitute(list(...)), deparse)[-1]
    l 
}
named.list(a,b,c)

Produces:

$a
[1] 2

$b
[1] "foo"

$c
[1] 1 2 3 4
waferthin
  • 1,582
  • 1
  • 16
  • 27
  • 1
    +1 For reproducible example. I don't think this is a particularly *bad* way of doing it myself. But you can avoid the `sapply` call. – Simon O'Hanlon Jul 24 '13 at 10:35

2 Answers2

20

A couple of ways I can think of include mget (make assumptions about the environment your objects are located in):

mget( c("a","b","c") )
$a
[1] 2

$b
[1] "foo"

$c
[1] 1 2 3 4

Or as an edit to your function, you could use, match.call like this:

named.list <- function(...) { 
    l <- list(...)
    names(l) <- as.character( match.call()[-1] )
   l
}
named.list( a,b,c)
$a
[1] 2

$b
[1] "foo"

$c
[1] 1 2 3 4

Or you can do it in one go using setNames like this:

named.list <- function(...) { 
    l <- setNames( list(...) , as.character( match.call()[-1]) ) 
    l
}

named.list( a,b,c)
$a
[1] 2

$b
[1] "foo"

$c
[1] 1 2 3 4
Simon O'Hanlon
  • 58,647
  • 14
  • 142
  • 184
  • +1! I would `as.list(match.call())[-1]`. and `expand.dots = TRUE` is set by default – agstudy Jul 24 '13 at 10:31
  • @agstudy thanks and I took heed of your tip about `expand.dots`! – Simon O'Hanlon Jul 24 '13 at 10:36
  • This won't allow you to name something in the call, e.g. ```r named.list(a, b, c = 1:4)``` will not name c. You could set ```l <- list(...)``` then add the names from match.call to elements without names in order to keep names for variables named in the call. – Wart May 19 '17 at 17:43
10

If you already using tidyverse packages, then you might be interested in using the tibble::lst function which does this

tibble::lst(a, b, c)
# $a
#  [1] 2
#  
# $b
# [1] "foo"
# 
# $c
# [1] 1 2 3 4
MrFlick
  • 195,160
  • 17
  • 277
  • 295