How to create a list with names but no entries in R/Splus?

57.5k views Asked by At

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?

4

There are 4 answers

2
Thilo On BEST ANSWER

I would do it like this:

mylist.names <- c("a", "b", "c")
mylist <- vector("list", length(mylist.names))
names(mylist) <- mylist.names
5
Wojciech Sobala On

A little bit shorter version than Thilo :)

mylist <- sapply(mylist.names,function(x) NULL)
1
Tommy On

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
0
Julien On
vector("list", length(mylist.names)) |> setNames(mylist.names)
$a
NULL

$b
NULL

$c
NULL

Inspired by this comment