check_value: Check the input value to a parent function argument

View source: R/checks.R

check_valueR Documentation

Check the input value to a parent function argument

Description

Within a function, this function checks the value of an input to an argument of that function. If the input value is supported, the function simply returns this value. If the input is not supported, the function either throws an error or returns a warning and the default value.

Usage

check_value(
  arg = deparse(substitute(input)),
  input,
  supp,
  warn = TRUE,
  default = supp[1]
)

Arguments

arg

A character string which defines the argument of the parent function.

input

The input to an argument of a parent function.

supp

A vector of supported input values for the argument in the parent function.

warn

A logical input which defines whether or not to return a warning and the default value (see default) or an error.

default

The default input value for the parent function.

Value

The function returns input, an error or a warning and default depending on whether or not input is within supp (i.e., whether or not the input to the argument of a parent function is supported).

Author(s)

Edward Lavender

Examples


#### Simple examples outside of parent functions
# Scenario: input to test is supported:
check_value(arg = "test", input = 1, supp = 1:2, warn = TRUE)
# Scenario: input to test is not supported, so return a warning and the default value
check_value(arg = "test", input = 1, supp = 2, warn = TRUE)
# Scenario: input to test is not supported:
## Not run: 
check_value(arg = "test", input = 1, supp = 2, warn = FALSE)

## End(Not run)

#### Examples inside a parent function
# The function returns 1 or 2, depending on the input to 'output'
return_1_or_2 <- function(output = 1){
  # Check the output, changing the output to the default if necessary
  output <- check_value(arg = "output", input = output, supp = 1:2, default = 1)
  # Return a value according to 'output'
  if(output == 1) return(1) else if(output == 2) return(2)
}
# Scenario: If a supported input to output is provided, everything works perfectly:
return_1_or_2(1); return_1_or_2(2)
# Scenario: If an unsupported input to output is provided,
# ... the default output is used with a warning:
## Not run: 
return_1_or_2(3)

## End(Not run)


edwardlavender/utils.add documentation built on Dec. 14, 2024, 8:11 a.m.