enforce_types | R Documentation |
This function allows for simple type enforcement in R inspired by C++ and other compiled languages. There are currently six primitive types which the function handles:
enforce_types(level = c("error", "warn", "none"))
level |
Should type failures error, warn, or be skipped (none)? |
int()
: An integer specified with the L syntax (i.e., '1L“)
chr()
: A string or character
lgl()
: A boolean TRUE/FALSE
dbl()
: A double or numeric value
tbl()
: A data frame or tibble (types within the data frame are not checked)
You can also provide default arguments within the parenthesis of the type. This is shown in the example below. You can provide new arguments as well. The function has knowledge of the function declaration when it runs. Note: types are checked at runtime not when the function is declared.
foo <- function(
x = int(1L),
y = chr("Hello!"),
z = lgl(TRUE),
a = dbl(1.1),
b = tbl(mtcars),
c = NULL # This argument will not be checked
) {
# Simply place enforce_types() in your function header!
dataclass::enforce_types()
# Function logic ...
}
# This run the function with the type defaults
foo()
# This will check types but for new arguments
foo(2L, "Hi!", FALSE, 1.2, mtcars)
# This would fail because types are incorrect!
# foo(1.1, FALSE, NULL, "Hi", list())
# This function will only warn when there are type failures
bar <- function(x = int(1)) {
dataclass::enforce_types("warn")
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.