Learn R Programming

statnet.common (version 4.13.0)

enlist: Wrap an object into a singleton list if not already a list

Description

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"))

Arguments

x

an object to be wrapped.

test

how a string or a function to decide whether an object counts as a list; see Details.

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.

a function with 1 argument

call as.logical(test(x)); if TRUE, the object is treated as a list; otherwise not.

Examples

Run this code

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))
)

Run the code above in your browser using DataLab