Learn R Programming

favr (version 1.0.0)

abort_if_not: Ensure the truth of R expressions

Description

If any of the expressions in ... are not all TRUE, abort is called for the first expression which was not (all) TRUE. The names of expressions can be used as the error message or a single default error message can be given using .message. Both are passed to format_inline for formatting.

Usage

abort_if_not(..., .message = NULL, .error_call = caller_env())

abort_if(..., .message = NULL, .error_call = caller_env())

Value

NULL, called for side effects only.

Arguments

...

any number of R expressions, which should each evaluate to (a logical vector of all) TRUE for no error to occur. Positive numbers are not TRUE, even when they are coerced to TRUE inside if() or in arithmetic computations in R. If the expressions are named, the names will be used in the error message.

.message

single default error message for non-named expressions.

.error_call

the call environment to use for error messages (passed to abort).

Details

abort_if is the opposite of abort_if_not, i.e. expressions should evaluate to (all) FALSE for no error to occur. See enforce and schema for a non data-masked and data-masked version of abort_if_not with options for size recycling and type casting.

Examples

Run this code
# NB: Some of these examples are expected to produce an error. To
#     prevent them from terminating a run with example() they are
#     piped into a call to try().

abort_if_not(1 == 1, all.equal(pi, 3.14159265), 1 < 2) # all TRUE

m <- matrix(c(1, 3, 3, 1), 2, 2)
abort_if_not(m == t(m), diag(m) == rep(1, 2)) # all TRUE

abort_if_not(1) |> try()

# A custom error message can be given for each expression:
m[1, 2] <- 12
abort_if_not("{.var m} must be {.cls symmetric}" = m == t(m)) |>
  try()

# Alternatively, one error message can be used for all
# expressions:
abort_if_not(
  m[1, 1] == 1,
  diag(m) == rep(2, 2),
  .message = "{.var m} has a diagonal of: {diag(m)}"
) |> try()

# The `.error_call` argument can be used to specify where the
# error occurs, by default this is the caller environment:
myfunc <- function(x) abort_if_not(x)
myfunc(FALSE) |> try()

# abort_if() errors if any argument does not evaluate to
# (all) FALSE:
abort_if(1 == 1) |> try()

# Injection can be used:
x <- "my error"
abort_if_not({{ x }} := FALSE) |> try()
abort_if_not(!!x := FALSE) |> try()
abort_if_not(FALSE, .message = "{x}") |> try()

x <- list("my {.var bang-bang-bang} error" = FALSE)
abort_if_not(!!!x) |> try()

Run the code above in your browser using DataLab