This function tests whether its first argument is a list according to the specified criterion; if not, puts it into a list of length 1.
Usage
enlist(x, test = c("inherits", "vector", "list"))Details
test can be one of the following
"inherits"use
inherits(x, "list"). This will require the object to have classlistand is generally the strictest (i.e., will wrap the most objects)."list"use
is.list(x). This will treat S3 objects based on lists as lists."vector"use
is.vector(x). This will treat atomic vectors andexpressions as lists.- a function with 1 argument
call
as.logical(test(x)); ifTRUE, the object is treated as a list; otherwise not.
Examples
data(mtcars)
stopifnot(
# Atomic vectors don't inherit from lists.
identical(enlist(1:3), list(1:3)),
# Atomic vectors are not lists internally.
identical(enlist(1:3, "list"), list(1:3)),
# Atomic vectors are a type of R vector.
identical(enlist(1:3, "vector"), 1:3),
# Data frames don't inherit from lists.
identical(enlist(mtcars), list(mtcars)),
# Data frames are lists internally.
identical(enlist(mtcars, "list"), mtcars),
# Data frames are not considered R vectors.
identical(enlist(mtcars, "vector"), list(mtcars))
)
# We treat something as a "list" if its first element is odd.
is.odd <- function(x) as.logical(x[1] %% 2)
stopifnot(
# 1 is a list.
identical(enlist(1, is.odd), 1),
# 2 is not.
identical(enlist(2, is.odd), list(2))
)