Easily check if an object has an expected class. This function checks that (all) the class(es) of the object are not in the expected_class vector.

cls_check(object, expected_class)

Arguments

object

The object whose class should be checked.

expected_class

A character vector of expected (or allowed) classes.

Value

The object's class(es), invisibly.

Examples

if (interactive()) { int_vec <- 1:5 chr_vec <- c("a", "b", "c", "d", "e") df <- data.frame(int_vec, chr_vec) # No error cls_check(int_vec, expected_class = "integer") # Error cls_check(int_vec, expected_class = "character") # No error cls_check(chr_vec, expected_class = "character") # Error cls_check(chr_vec, expected_class = "integer") # No error cls_check(df, expected_class = "data.frame") cls_check(df, expected_class = c("data.frame", "integer", "character")) # Error cls_check(df, expected_class = c("integer", "character")) if (requireNamespace("tibble")) { library(tibble) tbl_cars <- tibble(mtcars) # See the classes of tbl_cars # 'tbl_df', 'tbl', and 'data.frame' class(tbl_cars) # Check that tbl_cars has at least one of the expected class # This will return an error cls_check(object = tbl_cars, expected_class = c("character", "raw", "logical")) # This won't return an error since 'data.frame' is a class # of tbl_cars. It will invisibly return the 'tbl_cars' classes. cls_check(object = tbl_cars, expected_class = c("character", "raw", "data.frame")) } }