问题
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
)
回答1:
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
来源:https://stackoverflow.com/questions/59914349/r-named-lists-and-description-lists