Verify that input arguments meet certain conditions

This function is useful to quickly write input argument checks with informative error messages.

verifyArg(
  x,
  allowNull = FALSE,
  expectedClass,
  expectedMode,
  expectedLength,
  expectedSign,
  expectedNames,
  expectedTestFun,
  addlInfoBefore = NULL,
  addlInfoAfter = NULL
)

Arguments

x

Any object

allowNull

TRUE: x can be null. If TRUE and x is null, no additional tests are made.

expectedClass

Missing or character denoting the class of x

expectedMode

Missing or character denoting the mode of x

expectedLength

Missing or integer denoting the length of x

expectedSign

Missing or 1 or -1 denoting the sign of x

expectedNames

Names which must at least be present in x

expectedTestFun

A function for which the call expectedTestFun(x) returns TRUE (test is passed) or FALSE (test is failed)

addlInfoBefore, addlInfoAfter

Character to enrich the error message with useful information.

Value

Called for side-effect. If all tests pass, nothing happens. If errors occur, they are collected in informative error messages.

See also

Other Other functions: expand.grid2()

Author

Daniel Lill (daniel.lill@intiquan.com)

Examples

if (FALSE) { # \dontrun{

# Intended use case: Within a function
f <- function(myFancyArgument) {verifyArg(myFancyArgument, expectedMode = "character", expectedLength = 2)}
f(c(2)) # Two errors
f(c(2,3)) # One error
f(as.character(c(2))) # One error
f(as.character(c(2,3))) # No error

# Works also with more complex expressions:
f2 <- function(myFancyDF) {verifyArg(myFancyDF$TIME, expectedMode = "numeric")}
f2(data.frame(TIME = letters))


# Checking for integers is a bit tricky and should not necessarily be done with expectedClass

# Doubles
verifyArg(1, expectedClass = "numeric")    # Gives no error
verifyArg(1, expectedClass = "double")     # Gives error
verifyArg(1, expectedMode = "numeric")     # Gives no error
verifyArg(1, expectedTestFun = is.numeric) # Gives no error, last resort

# Integers
verifyArg(1L, expectedClass = "numeric") # Gives error
verifyArg(1L, expectedMode = "numeric")  # Gives no error
} # }