17

In interactive use, I occasionally need to bundle a largish set of objects together in a list. To get a list in which the elements keep their original names, I am forced to write something like list(Object1=Object1, Object2=Object2, ..... , Object25=Object25).

Is there some straightforward way to place a set of named objects in a list, such that they 'keep' their names, without having to type nameXXX=nameXXX for each one?

cars <- mtcars[1:2,1:2]
vowels <- c("a","e","i","o","u")
consonants <- setdiff(letters, vowels)

## I'd like to get this result...
list(consonants=consonants, vowels=vowels, cars=cars)
## $consonants
##  [1] "b" "c" "d" "f" "g" "h" "j" "k" "l" "m" "n" "p" "q" "r" "s" "t" "v" "w" "x"
## [20] "y" "z"
##
## $vowels
## [1] "a" "e" "i" "o" "u"
##
## $cars
##               mpg cyl
## Mazda RX4      21   6
## Mazda RX4 Wag  21   6

## ... but by doing something more like
f(consonants, vowels, cars)
1
  • Thanks, @BenBolker -- I'd accept your answer if I could. Commented Jun 10, 2015 at 20:50

3 Answers 3

19

You can get the same structure with

mget(c("vowels", "consonants", "cars"))

but you do have to do have to quote the variable names which isn't super sexy.

Sign up to request clarification or add additional context in comments.

2 Comments

This modification allows unquoted names: mget(sapply(expression(vowels, consonants, cars), paste))
Interesting. I'm kind of surprised paste works like that. I would have expected a deparse.
11

Here's what I used most recently.

It would be nice, though, if there were something more succinct (or something built into base R or a decent package), so please feel free to add other/better answers.

LIST <- function(...) {
    nms <- sapply(as.list(substitute(list(...))), deparse)[-1]
    setNames(list(...), nms)
}

LIST(vowels, consonants, cars)
# $vowels
# [1] "a" "e" "i" "o" "u"
# 
# $consonants
#  [1] "b" "c" "d" "f" "g" "h" "j" "k" "l" "m" "n" "p" "q" "r" "s" "t" "v" "w" "x"
# [20] "y" "z"
# 
# $cars
#               mpg cyl
# Mazda RX4      21   6
# Mazda RX4 Wag  21   6

Comments

2

How about:

namedList  <-  function(...){
    out  <-  list(...)
    for(i in seq(length(out)))
        names(out)[i]  <-  as.character(sys.call()[[i+1]])
    out
}

foo = 1
bar = 'Hello world'
namedList(foo,bar)

#> $foo
#> [1] 1
#> 
#> $bar
#> [1] "Hello world"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.