Skip to contents

Checks if an argument is a character scalar and (optionally) whether it matches one of the provided values.

Usage

assert_character_scalar(
  arg,
  values = NULL,
  case_sensitive = TRUE,
  optional = FALSE,
  arg_name = rlang::caller_arg(arg),
  message = NULL,
  class = "assert_character_scalar",
  call = parent.frame()
)

Arguments

arg

A function argument to be checked

values

A character vector of valid values for arg. Values is converted to a lower case vector if case_sensitive = FALSE is used.

case_sensitive

Should the argument be handled case-sensitive? If set to FALSE, the argument is converted to lower case for checking the permitted values and returning the argument.

optional

Is the checked argument optional? If set to FALSE and arg is NULL then an error is thrown

arg_name

string indicating the label/symbol of the object being checked.

message

string passed to cli::cli_abort(message). When NULL, default messaging is used (see examples for default messages). "{arg_name}" can be used in messaging.

class

Subclass of the condition.

call

The execution environment of a currently running function, e.g. call = caller_env(). The corresponding function call is retrieved and mentioned in error messages as the source of the error.

You only need to supply call when throwing a condition from a helper function which wouldn't be relevant to mention in the message.

Can also be NULL or a defused function call to respectively not display any call or hard-code a code to display.

For more information about error calls, see Including function calls in error messages.

Value

The function throws an error if arg is not a character vector or if arg is a character vector but of length > 1 or if its value is not one of the values specified. Otherwise, the input is returned invisibly.

Examples

example_fun <- function(msg_type) {
  assert_character_scalar(msg_type, values = c("warning", "error"))
}

example_fun("warning")

try(example_fun("message"))
#> Error in example_fun("message") : 
#>   Argument `msg_type` must be equal to one of "warning" or "error".

try(example_fun(TRUE))
#> Error in example_fun(TRUE) : 
#>   Argument `msg_type` must be a scalar of class <character>, but is
#> `TRUE`.

# handling arguments case-insensitive
example_fun2 <- function(msg_type) {
  msg_type <- assert_character_scalar(
    msg_type,
    values = c("warning", "error"),
    case_sensitive = FALSE
  )
  if (msg_type == "warning") {
    print("A warning was requested.")
  }
}

example_fun2("Warning")
#> [1] "A warning was requested."