vb: Validate input as boolean and replace with default on empty...

vbR Documentation

Validate input as boolean and replace with default on empty input if desired

Description

This function is intended to be a more flexible replacement for calling is.logical(). In particular, it makes it possible to replace empty values with a default value (e.g., FALSE) and to define whether NULL and/or NA are treated as empty values. It also allows control over whether numeric values are considered boolean by this validation function. This is sometimes useful when validating an input option where a numeric value would be suggestive of a mistake in the input file.

Usage

vb(
  var_value,
  def_on_empty = FALSE,
  def = FALSE,
  treat_NULL_as_empty = TRUE,
  treat_NA_as_empty = FALSE,
  allow_num = FALSE
)

Arguments

var_value

the value to be checked to see if it's a boolean

def_on_empty

boolean flag indicating whether to return a default value instead of the input value when the input value is empty (where empty is defined by other flags below)

def

a TRUE or FALSE default value to return instead of the input value when a default is requested

treat_NULL_as_empty

a boolean flag set to TRUE if a NULL input is to be treated as an empty input; FALSE otherwise

treat_NA_as_empty

a boolean flag set to TRUE if an NA input is to be treated as an empty input; FALSE otherwise

allow_num

a boolean flag set to TRUE if a numeric input is to be allowed and returned as FALSE if 0 and TRUE if non-zero

Details

Note that even if they are set to TRUE, the flags treat_NULL_as_empty and treat_NA_as_empty are ignored if def_on_empty is FALSE.

Value

Returns the input value if it is boolean or, returns a specified boolean if other arguments force a valid converted or default boolean to return; otherwise, throws an error

Examples

x <- TRUE
vb (x)
vb (-150, allow_num = TRUE)
vb (0, allow_num = TRUE)
vb (NULL, def_on_empty = TRUE)
vb (NULL, def_on_empty = TRUE, def = TRUE)
vb (NA, def_on_empty = TRUE, def = TRUE, treat_NA_as_empty = TRUE)
vb (NA, def_on_empty = TRUE, treat_NA_as_empty = TRUE)
vb (NULL, def_on_empty = TRUE, def = 10, treat_NULL_as_empty = TRUE, allow_num = TRUE)
## Not run: 
                #  These all generate errors
vb (1)                     #  error - not boolean & allow_num not set to TRUE
vb (0)
vb (1000)
vb ("aString")                        #  error - not boolean
vb (NULL)                             #  error - def_on_empty not set
vb (NA)            #  error - def_on_empty not set, treat_NA_as_empty not set
vb (NULL, treat_NULL_as_empty = TRUE) #  error - def_on_empty not set
vb (NA, treat_NA_as_empty = TRUE)     #  error - def_on_empty not set to TRUE
        #  error - non-numeric default, but allow_num not TRUE
vb (NA, def_on_empty = TRUE, def = 10, treat_NA_as_empty = TRUE)
         
## End(Not run)

langfob/bdpg documentation built on Dec. 8, 2022, 5:33 a.m.