How to create a list with names but no entries in R/Splus?
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?
I would do it like this:
mylist.names <- c("a", "b", "c")
mylist <- vector("list", length(mylist.names))
names(mylist) <- mylist.names
A little bit shorter version than Thilo :)
mylist <- sapply(mylist.names,function(x) NULL)
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