View source: R/misc.utilities.R
| enlist | R Documentation |
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.
enlist(x, test = c("inherits", "vector", "list"))
x |
an object to be wrapped. |
test |
how a string or a function to decide whether an object counts as a list; see Details. |
test can be one of the following
"inherits"use inherits(x, "list"). This will
require the object to have class list and 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 and expressions as lists.
call as.logical(test(x)); if
TRUE, the object is treated as a list; otherwise not.
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))
)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.