check_class | R Documentation |
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.
check_class(
arg = deparse(substitute(input)),
input,
if_class = NULL,
to_class,
type = "stop",
coerce_input
)
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 |
to_class |
The required class of the input. |
type |
A character which specifies whether to return an error ( |
coerce_input |
A function used to coerce |
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.
Edward Lavender
#### 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)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.