How do you make an empty named list?

157 views Asked by At

In R, the term "empty list" is usually understood to mean list(). But this isn't what you get when you delete all the elements from a named list:

x = list(a = 1)
x$a = NULL
print(x)                     # named list()
print(identical(x, list()))  # FALSE

Is there a slicker or more idiomatic way to get an empty named list?

3

There are 3 answers

0
jay.sf On BEST ANSWER

Using setNames.

setNames(list(), character(0))
# named list()
3
ThomasIsCoding On

Probably the code below can play the trick

> `[<-`(list(a = NULL), NULL)
named list()

> list(a = NULL)[NULL]
named list()
6
Nir Graham On

I think you are trying to do


a <- list()
attr(a,"names") <- character(0)
a

I dont see the value of it though