0

By default, R creates an unnamed list:

x <- 42
y <- "John"
z <- 1:7
list(x, y, z)
# [[1]]
# [1] 42
# 
# [[2]]
# [1] "John"
# 
# [[3]]
# [1] 1 2 3 4 5 6 7

This below seems to do what I want, but I feel I missed something crucial, as why isn't this the default behaviour?

namedlist <- function(...) {
  L <- list(...)
  names(L) <- unlist( lapply( as.list( match.call())[-1L],
                              as.character))
  return( L )
}
Jisca
  • 3
  • 4

2 Answers2

4

I don't know how to answer your "why" question but it is what the default behavior of list is. By default R, creates an unnamed list if you don't create the names input explicitly.

So you can create a named list using

list(x = x, y = y, z = z)

Or tibble has lst function which behaves same as your namedlist

tibble::lst(x, y, z)
#$x
#[1] 42

#$y
#[1] "John"

#$z
#[1] 1 2 3 4 5 6 7
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1

Yes, by default R's lists are unnamed.

To create a named list, there's no need for your own custom function namedlist().

You're getting confused between merely referencing the values of x, y, z:

l1 <- list(x, y, z)

vs actually declaring named elements in a list:

l1 <- list(x=42, y="John", z=1:7)

(or else using setNames() on an unnamed list).

smci
  • 32,567
  • 20
  • 113
  • 146