check_class: Check the class of an function input to a parent function

View source: R/checks.R

check_classR Documentation

Check the class of an function input to a parent function

Description

This function checks that the class of an input to a parent function is appropriate. If not, the function either produces a helpful error message or returns a warning.

Usage

check_class(
  arg = deparse(substitute(input)),
  input,
  if_class = NULL,
  to_class,
  type = "stop",
  coerce_input
)

Arguments

arg

A character string which defines the argument of the parent function.

input

The input to an argument of a parent function.

if_class

(optional) A character vector of classes of object. If supplied, the function will only proceed to check the class of the object if the class(input) is one of if_class. This is useful if check_class() is implemented in a loop.

to_class

The required class of the input.

type

A character which specifies whether to return an error ("stop") or a warning ("warning").

coerce_input

A function used to coerce input to the correct object type, if type = "warning".

Value

The function checks the class of the input. If the class is not the same as required by the parent function (i.e., as specified by class), the function returns a helpful error message, or a warning and an object whose class has been coerced to the correct class.

Author(s)

Edward Lavender

Examples

#### Example (1): Implementation using default options outside of a function
# Imagine we have an argument, x, to a function, the input to which must be a list.
# This input passes the check:
check_class(arg = "x", input = list(), to_class = "list")
## Not run: 
# This input fails the check:
check_class(arg = "x", input = list(), to_class = "Date")

## End(Not run)

#### Example (2): Implementation within a parent function
nest_list_in_list <- function(x){
  check_class(arg = "x", input = x, to_class = "list")
  if(inherits(x, "list")){
    return(list(x))
  }
}
nest_list_in_list(list())
## Not run: 
nest_list_in_list("a")

## End(Not run)

#### Example (3) Return a warning rather than an error
x <- as.POSIXct("2016-01-01")
check_class(arg = "x", input = x, to_class = "Date",
                  type = "warning", coerce_input = as.Date)

#### Example (4) Only act on objects of a certain class; otherwise, return objects unchanged.
# In this case the function checks x:
check_class(arg = "x", input = x,
                  if_class = c("POSIXct", "Date"),
                  to_class = "Date", type = "warning", coerce_input = as.Date)
# In this case the function does not check x
check_class(arg = "x", input = 5,
                  if_class = c("POSIXct", "Date"),
                  to_class = "Date", type = "warning", coerce_input = as.Date)


edwardlavender/utils.add documentation built on Dec. 14, 2024, 8:11 a.m.