validateObject | R Documentation |
This function validates an object using a list of checks. If any check
fails, an error handler is called and a default value is returned. This
function is intended to slightly simplify cases where a long list of
complex and convoluted predetermined checks are needed. For simpler cases
like type checking, it is recommended to use stopifnot()
or
assertthat::assert_that()
.
validateObject(obj, checks, errorHandler = warningp, defaultReturn = NULL)
obj |
The object to validate. |
checks |
A single function or list of functions, each taking the object as an argument and returning NULL if the check passes or an error message if the check fails. |
errorHandler |
A function to handle errors, taking the error message as
an argument. Default is |
defaultReturn |
The value to return if any check fails. Default is NULL. |
The original object if all checks pass, or defaultReturn
if any
check fails.
# Define some checks
checkNotNull <- function(x) if (is.null(x)) "Object is NULL" else NULL
checkIsNumeric <- function(x) {
if (!is.numeric(x)) "Object is not numeric" else NULL
}
# Validate an object
obj <- 42
validateObject(obj, list(checkNotNull, checkIsNumeric))
# Validate an object that fails a check
obj <- NULL
try(
validateObject(
obj,
list(checkNotNull, checkIsNumeric, errorHandler = stop)
),
silent = TRUE
)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.