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
1
  • 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. Commented Jul 24, 2013 at 10:35

2 Answers 2

21

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

3 Comments

+1! I would as.list(match.call())[-1]. and expand.dots = TRUE is set by default
@agstudy thanks and I took heed of your tip about expand.dots!
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.
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

2 Comments

Is there a function that does the opposite, creates variables from named list? I can also post a question if you want.
@mihagazvoda: list2env does what you want

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.