cls_check: Informative Class Checking

Description Usage Arguments Value Examples

View source: R/func_classes.R

Description

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.

Usage

1
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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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"))

  }

}

jdtrat/jdtools documentation built on Dec. 20, 2021, 10:05 p.m.