Skip to contents

This function checks if the specified arguments of a function match the expected type. It is useful for validating function inputs.

Usage

check_args(args_all, args_to_check, args_type, include_backtrace = FALSE)

Arguments

args_all

Character vector. Input parameters of the function. Usually as a result of formals() function

args_to_check

Character vector. Names of the arguments to be checked.

args_type

Character. The expected type of the arguments. Must be one of "character", "logical", or "numeric".

include_backtrace

Logical. If TRUE, includes the backtrace in the error message. Default is FALSE. See stop_ctx for more details.

Value

The function does not return a value but will stop execution and throw an error if any of the specified arguments do not match the expected type.

Author

Ahmed El-Gabbas

Examples

# define a function with arguments
f1 <- function(x = "AA", y = "BB", z = 1) {
  all_arguments <- ls(envir = environment())
  all_arguments <- purrr::map(
    all_arguments,
    function(x) get(x, envir = parent.env(env = environment()))) %>%
    stats::setNames(all_arguments)

 # Check if x and y are a character
 check_args(
    args_all = all_arguments, args_type = "character",
    args_to_check = c("x", "y"))

 # Check if z is a numeric
 check_args(
    args_all = all_arguments, args_type = "numeric",
    args_to_check = "z")

 # the rest of the function
}

#  |||||||||||||||||||||||||||||||||||||||||||||||||

# no output as x is a character
f1(x = "X")

# no output as z is a numeric
f1(z = 20)

if (FALSE) { # \dontrun{
  # error as x is not a character
  f1(x = 1)
} # }