Learn R Programming

cryptoQuotes (version 1.3.0)

assert: Assert truthfulness of conditions before evaluation

Description

This function is a wrapper of stopifnot(), tryCatch() and cli::cli_abort() and asserts the truthfulness of the passed expression(s).

Usage

assert(..., error_message = NULL)

Value

NULL if all statements in ... are TRUE

Arguments

...

expressions >= 1. If named the names are used as error messages, otherwise R's internal error-messages are thrown

error_message

character. An error message, supports cli-formatting.

See Also

Examples

Run this code
# script: Assert truthfullness
# of functions
# date: 2024-02-22
# author: Serkan Korkmaz, serkor1@duck.com
# objective: Demonstrate the use of the error-function. This is
# mainly for contributers, and for my future self on how to use
# this function properly
#
#
# NOTE: As these are wrapped in try
# they are not properly formatted.
# script start;


# 1) unnamed assert
# expressions
foo <- function(
    a,
    b) {

  # assert without
  # named expressions
  cryptoQuotes:::assert(
    is.numeric(a),
    is.numeric(b)
  )

  a + b

}

# 1.1) returns
# the regular R error
# messages in cli-format
try(
  foo(
    a = "1",
    b = "2"
  )
)



# 2) named assert
# expressions
foo <- function(
    a,
    b) {

  cryptoQuotes:::assert(
    "{.arg a} is not {.cls numeric}" =  is.numeric(a),
    "{.arg a} is not {.cls numeric}" = is.numeric(b)
  )


  a + b

}

# 2.2) Returns
# custom error-messages
# in cli-format
try(
  foo(
    a = "1",
    b = "2"
  )
)


# 3) custom error
# messages on
foo <- function(
    a) {

  cryptoQuotes:::assert(
    is.numeric(a),
    error_message = sprintf(
      fmt = "{.val %s} is not a numeric value.",
      a
    )
  )

  a

}

# 2.2) Returns
# custom error-messages with
# passed values in cli-format
try(
  foo(
    a = "1"
  )
)





# script end;

Run the code above in your browser using DataLab