util_expect_scalar function

check, if a scalar/vector function argument matches expectations

check, if a scalar/vector function argument matches expectations

util_expect_scalar( arg_name, allow_more_than_one = FALSE, allow_null = FALSE, allow_na = FALSE, min_length = -Inf, max_length = Inf, check_type, convert_if_possible, conversion_may_replace_NA = FALSE, dont_assign = FALSE, error_message )

Arguments

  • arg_name: the argument
  • allow_more_than_one: allow vectors
  • allow_null: allow NULL
  • allow_na: allow NAs
  • min_length: minimum length of the argument's value
  • max_length: maximum length of the argument's value
  • check_type: a predicate function, that must return TRUE on the argument's value.
  • convert_if_possible: if given, a lambda can be given similar to check_type This lambda would be used to try a conversion. If a conversion fails (returns NA, where the input was not `util_empty'), an error is still thrown, the data is converted, otherwise
  • conversion_may_replace_NA: if set to TRUE, we can define a function in convert_if_possible that replaces NA values without causing a warning, but this option is set to FALSE by default to catch possible conversion problems (use it with caution).
  • dont_assign: set TRUE to keep x in the caller environment untouched
  • error_message: if check_type() returned FALSE, show this instead of a default error message.

Returns

the value of arg_name -- but this is updated in the calling frame anyway.

Examples

## Not run: f <- function(x) { util_expect_scalar(x, check_type = is.integer) } f(42L) try(f(42)) g <- function(x) { util_expect_scalar(x, check_type = is.integer, convert_if_possible = as.integer) } g(42L) g(42) ## End(Not run)

See Also

Other robustness_functions: util_as_valid_missing_codes(), util_check_one_unique_value(), util_correct_variable_use(), util_empty(), util_ensure_character(), util_ensure_in(), util_ensure_suggested(), util_fix_rstudio_bugs(), util_is_integer(), util_is_numeric_in(), util_is_valid_missing_codes(), util_match_arg(), util_observations_in_subgroups(), util_stop_if_not(), util_warn_unordered()

  • Maintainer: Stephan Struckmann
  • License: BSD_2_clause + file LICENSE
  • Last published: 2025-03-05