Skip to contents

Check if arg inherits from any of the classes in class.

Usage

check_inherits(arg, class, signal = "error", msg = NULL, call. = FALSE)

Arguments

arg

(object)
The argument to check.

class

(Character)
A character vector of class names. arg passes if it inherits from at least one of these classes, following base::inherits() semantics.

signal

(string: c("error", "warning", "message"))
Must be one of "error", "warning", or "message". "error" (default) calls base::stop() to signal an error message. "warning" calls base::warning() to signal a warning message. "message" calls base::message() to signal a message.

msg

(string or NULL: NULL)
A string that replaces the default message. Set as NULL to use the default message.

call.

(Scalar logical: c(FALSE, TRUE))
Passed to stop() or warning(). The default msg includes it's own formatted call, hence call. should be FALSE (default). If you insert your own msg, then you may want call. = TRUE.

Value

invisible(arg) or condition determined by argument signal.

Examples

#----------------------------------------------------------------------------
# check_inherits() examples
#----------------------------------------------------------------------------
library(bkcheck)

f <- function(x) {
  x |>
    check_inherits("data.frame")
}

f(data.frame(a = 1))
try(f(1:2))
#> Error : Argument `x` must be an object of class 'data.frame'.
#> 
#> class(x) = 'integer'
#> length(x) = 2
#> 
#> Call: f(x = 1:2)

# Pass if `arg` inherits from any one of several classes
g <- function(x) {
  x |>
    check_inherits(c("Date", "POSIXct"))
}

g(Sys.Date())
g(Sys.time())
try(g(1:2))
#> Error : Argument `x` must be an object of class 'Date' or 'POSIXct'.
#> 
#> class(x) = 'integer'
#> length(x) = 2
#> 
#> Call: g(x = 1:2)