5

R has two classes not so commonly used: "Dlist" and "namedList".

As regard the first, it is mentioned with respect to Sys.getenv(), which returns a result of class "Dlist" if its argument is missing, for nice printing. There is in fact a print.Dlist method for the class. There is also an apparently related formatDL function to format description lists. However I do not know how to create an object of class "Dlist".

As regards "namedList", it is defined by the manual:

the alternative to "list" that preserves the names attribute

In this case I am unable to create an object of this type and I have not found any instance where it is used.

How do you create a "Dlist" or a "namedList"?
Can you provide an example where the "namedList" is more convenient of an ordinary named list? (intended as a list L, where names(L) is not NULL)

antonio
  • 10,629
  • 13
  • 68
  • 136
  • @akrun: This sounds what I called the "ordinary named list", in fact, the function `namedList`, in BBmisc, returns an object of class "list". – antonio Jan 25 '20 at 23:49
  • @akrun: In DSL that is a distributed list class, intended to manage and store large objects. The standard R seems to address description lists. – antonio Jan 25 '20 at 23:53

1 Answers1

6

A Dlist is an informal class defined in R's Base package that exists for the sole purpose of pretty-printing a named character vector. It's not a list at all, but a type of character vector:

a <- Sys.getenv()
class(a)
# [1] "Dlist"
typeof(a)
# [1] "character"

You can make one just by writing Dlist to a named character vector's class attribute:

hello_world <- c(Hello = "World", Hi = "Earth", Greetings = "planet"); 
class(hello_world) <- "Dlist"

hello_world
# Hello                    World
# Hi                       Earth
# Greetings                planet

You can select formatting options with formatDL:

cat(formatDL(hello_world, style = "list", width = 20), sep = "\n")
# Hello: World
# Hi: Earth
# Greetings: planet

The Dlist is only used in base R for printing environmental variables to the console. Unless you wanted to have a named character vector printed this way, you don't need a Dlist.


On the other hand, a namedList is a formal S4 object as defined in the methods package (also preloaded in R). It inherits its attributes from list and defines a single method - its own version of the generic S4 show. You might use it as a base class from which to make new S4 classes that inherit the properties of a named list (i.e. a normal list with a names attribute), although it's not clear why a user advanced enough to create S4 classes wouldn't just do that themselves. It's defined here.

You can create a namedList with new:

n <- new("namedList", list(a=1, b=2))
n
# An object of class  “namedList” 
# $`a`
# [1] 1
# 
# $b
# [1] 2
isS4(n)
# [1] TRUE
Allan Cameron
  • 147,086
  • 7
  • 49
  • 87