46

I'd like to set up a list with named entries whose values are left uninitialized (I plan to add stuff to them later). How do people generally do this? I've done:

mylist.names <- c("a", "b", "c")
mylist <- as.list(rep(NA, length(mylist.names)))
names(mylist) <- mylist.names

but this seems kind of hacky. There has to be a more standard way of doing this...right?

lowndrul
  • 3,423
  • 6
  • 33
  • 52
  • Vaguely related: http://stackoverflow.com/questions/5042806/r-creating-a-named-vector-from-variables/5043280#5043280 – Andrie Apr 16 '11 at 18:37

3 Answers3

62

I would do it like this:

mylist.names <- c("a", "b", "c")
mylist <- vector("list", length(mylist.names))
names(mylist) <- mylist.names
Thilo
  • 8,329
  • 2
  • 33
  • 53
  • 24
    There is function to set names: `setNames(vector("list", length(mylist.names)), mylist.names)`. – Marek Apr 18 '11 at 11:10
  • 2
    It always depends on what you want to archive. I usually like to break up steps to make reading the code easier. R / Splus tends to let you write quite a lot of stuff in one line - which is fine for testing and getting done fast, but bad for readability. – Thilo Apr 18 '11 at 12:33
35

A little bit shorter version than Thilo :)

mylist <- sapply(mylist.names,function(x) NULL)
Wojciech Sobala
  • 7,063
  • 2
  • 20
  • 27
9

Another tricky way to do it:

mylist.names <- c("a", "b", "c") 

mylist <- NULL
mylist[mylist.names] <- list(NULL)

This works because your replacing non-existing entries, so they're created. The list(NULL) is unfortunately required, since NULL means REMOVE an entry:

x <- list(a=1:2, b=2:3, c=3:4)
x["a"] <- NULL # removes the "a" entry!
x["c"] <- list(NULL) # assigns NULL to "c" entry
Tommy
  • 38,649
  • 12
  • 87
  • 83