Learn R Programming

assertive (version 0.2-6)

assert_engine: Throws an error if a condition isn't met.

Description

The workhorse of the package. If a condition isn't met, then an error is thrown. This function is exported for use by package developers so that they can create their own assert functions.

Usage

assert_engine(x, predicate, msg, what = c("all", "any"), ...)

Arguments

x
Input to check. If missing, pass no args to predicate.
predicate
Function that returns a logical value (possibly a vector).
msg
The error message, in the event of failure.
what
Either 'all' or 'any', to reduce vectorised tests to a single value.
...
Passed to the predicate function.

Value

  • FALSE with the attribute message, as provided in the input.

Examples

Run this code
# Extending assertive with an is function that returns a single value
is_identical_to_pi <- function(x, .xname = get_name_in_parent())
{
  if(!identical(x, pi))
  {
    return(false("%s is not identical to pi", .xname))
  }
  TRUE
}
assert_is_identical_to_pi <- function(x, .xname = get_name_in_parent())
{
  assert_engine(
    x,
    is_identical_to_pi,
    .xname = get_name_in_parent(x)
  )
}

is_identical_to_pi(pi)
is_identical_to_pi(3)
assert_is_identical_to_pi(pi)
dont_stop(assert_is_identical_to_pi(3))

# Extending assertive with an is function that returns a vector
is_less_than_pi <- function(x)
{
  is_in_right_open_range(x, upper = pi)
}

assert_all_are_less_than_pi <- function(x)
{
  msg <- gettextf("%s are not all less than pi.", get_name_in_parent(x))
  assert_engine(
    x,
    is_less_than_pi,
    msg
  )
}
assert_any_are_less_than_pi <- function(x)
{
  msg <- gettextf("%s are all greater than or equal to pi.", get_name_in_parent(x))
  assert_engine(
    x,
    is_less_than_pi,
    msg,
    what = "any"
  )
}

x <- c(3, pi, 4, NA)
is_less_than_pi(x)
assert_any_are_less_than_pi(x)
dont_stop(assert_all_are_less_than_pi(x))

Run the code above in your browser using DataLab