Description Usage Arguments Details Value Examples
Use 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.
1 2 3 4 5 6 7 |
value. |
The value which is to be ensured. |
... |
conditions which must pass for the ensuring contract to be
fulfilled. Any named argument will treated as values available
when evaluating the conditions. To reference the value itself
use the dot-placeholder, |
fail_with |
A unary function (accepting a |
err_desc |
A character string with an additional error description. |
It is possible to specify custom error message to specific conditions
to make them more readable and user-friendly. To do this use a formula
condition ~ message
, where 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
and ensures
are short-hand aliases for
their *_that
counterparts.
ensures_that
returns an ensuring function; ensure_that
returns the value itself on success.
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 46 47 48 49 | ## Not run:
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)
|
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.