45

It would be very helpful to me to be able to create an R list object without having to specify the names of each element. For example:

a1 <- 1
a2 <- 20
a3 <- 1:20

b <- list(a1,a2,a3, inherit.name=TRUE)
> b

[[a1]]
[1] 1

[[a2]]
[1] 20

[[a3]]
 [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20

This would be ideal. Any suggestions?

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
Francis Smart
  • 3,875
  • 6
  • 32
  • 58

4 Answers4

41

The tidyverse package tibble has a function that can do this as well. Try out tibble::lst

tibble::lst(a1, a2, a3)
# $a1
#  [1] 1
#
# $a2
#  [1] 20
# 
# $a3
#  [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20
MrFlick
  • 195,160
  • 17
  • 277
  • 295
27

Coincidentally, I just wrote this function. It looks a lot like @joran's solution, but it tries not to stomp on already-named arguments.

namedList <- function(...) {
    L <- list(...)
    snm <- sapply(substitute(list(...)),deparse)[-1]
    if (is.null(nm <- names(L))) nm <- snm
    if (any(nonames <- nm=="")) nm[nonames] <- snm[nonames]
    setNames(L,nm)
}
## TESTING:
a <- b <- c <- 1
namedList(a,b,c)
namedList(a,b,d=c)
namedList(e=a,f=b,d=c)

Copied from comments: if you want something from a CRAN package, you can use Hmisc::llist:

Hmisc::llist(a, b, c, d=a, labels = FALSE)

The only apparent difference is that the individual vectors also have names in this case.

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
  • 4
    There is also Hmisc::llist eg llist(a1,a2, labels = FALSE). This protects against already-named arguments, – mnel Jun 06 '13 at 00:15
  • Thanks so much! I really like this one. I will implement it in a [package](https://github.com/EconometricsBySimulation/RConcerto/blob/master/Package.R) I am working on – Francis Smart Jun 06 '13 at 07:58
  • 2
    This will fail if the input arguments are longer than ~60 character because in that case `deparse()` will generate a vector of length >1, and `sapply()` will make a list instead of a character vector. – hadley Jul 28 '15 at 15:31
12

A random idea:

a1<-1
a2<-20
a3<-1:20

my_list <- function(...){
    names <- as.list(substitute(list(...)))[-1L]
    result <- list(...)
    names(result) <- names
    result
}

> my_list(a1,a2,a3)
$a1
[1] 1

$a2
[1] 20

$a3
 [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20

(The idea is stolen from the code in data.frame.)

joran
  • 169,992
  • 32
  • 429
  • 468
5

Another idea ,

 sapply(ls(pattern='^a[0-9]'), get)
$a1
[1] 1

$a2
[1] 20

$a3
 [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20
agstudy
  • 119,832
  • 17
  • 199
  • 261