Last chance! 50% off unlimited learning
Sale ends in
ensure_that
(imperitive form) to ensure conditions for a value "on
the fly". The present tense form, ensures_that
is used to make
reusable "contracts" (functions) which can subsequently be applied to values;
see examples below. It is also possible to check (rather than ensure) whether
conditions are satisfied; the check_that
function works like
ensure_that
but will return TRUE
or FALSE
.
check_that(., ...)
check(., ...)
ensure_that(., ..., fail_with = function(e) stop(e), err_desc = "")
ensure(., ..., fail_with = function(e) stop(e), err_desc = "")
ensures_that(..., fail_with = function(e) stop(e), err_desc = "")
ensures(..., fail_with = function(e) stop(e), err_desc = "")
`.`
. See 'Details' for some special named
arguments.simpleError
)
or a static value.ensures_that
returns an ensuring function; ensure_that
returns the value itself on success. check_that
returns TRUE
on success, and FALSE
otherwise.
condition ~ err.message
, where err.message
is a single
character value.Existing contracts can be added as a condition argument, which will add the
conditions from the existing contract to the new contract (along with any
assigned values). To do this use (unary) +
to indicate that an
argument is a contract. See example below.
It is important to note that a condition is only satisfied if it evaluates to
TRUE
(tested with isTRUE
), i.e. a vector with several
TRUE
s will fail, so be sure to use all
or any
in such a
case.
The functions ensure
ensures
, and check
are short-hand
aliases for their *_that
counterparts.
## Not run:
#
# ensure_that(1:10, is.integer)
#
# # Examples below will use the magrittr pipe
# library(magrittr)
#
# # Create a contract which can ensure that a matrix is square.
# ensure_square <- ensures_that(NCOL(.) == NROW(.))
#
# # apply it.
# A <-
# diag(4) %>%
# ensure_square
#
# # Without the pipe operator:
# A <- ensure_square(diag(4))
#
# # Ensure on the fly (this will pass the test)
# A <-
# matrix(runif(16), 4, 4) %>%
# ensure_that(ncol(.) == nrow(.), all(. <= 1))
#
# # This will raise an error
# A <-
# matrix(NA, 4, 4) %>%
# ensure_that(. %>% anyNA %>% not)
#
# # Tweak failure:
# A <-
# 1:10 %>%
# ensure_that(all(. < 5), err_desc = "Number tests!")
#
# # A default value for failure situations:
# A <-
# 1:10 %>%
# ensure_that(all(. < 5), fail_with = NA)
#
# # Suppose you had an email function:
# email_err <- function(e) {email(e$message); stop(e)}
#
# A <-
# 1:10 %>%
# ensure_that(all(. < 5), fail_with = email_err)
#
# # Two similar contracts, one extending the other.
# # Note also that custom message is used for A
# A <- ensures_that(all(.) > 0 ~ "Not all values are positive")
# B <- ensures_that(!any(is.na(.)) ~ "There are missing values", +A)
#
# B(c(-5:5, NA))
# ## End(Not run)
Run the code above in your browser using DataLab