R: Argument Checking

addError {ArgumentCheck} | R Documentation

## Argument Checking

### Description

Checking function arguments can be done in a manner that allows all of the problems in the arguments to be noted and returned to the user in a single call. This avoids the potentially iterative process of finding problems in one argument, fixing the error, and going on to find problems in subsequent checks. The `ArgCheck` object can store messages for all of the problems and return these messages all at once, allowing the user the opportunity to fix all of the arguments before proceeding.

### Usage

    addError(msg, argcheck)

    addMessage(msg, argcheck)

    addWarning(msg, argcheck)

    finishArgCheck(argcheck)

    newArgCheck()

### Arguments

`msg` | A Character string giving the message to return with an error or warning
`argcheck` | An object with class `ArgCheck`, usually created by `newArgCheck`

### Details

`newArgCheck` initializes an `ArgCheck` object. This object stores the number of warnings, the number of errors, and the corresponding messages for the warnings and errors.

`addError` and `addWarning` are used to add messages to the `ArgCheck` objects.

`finishArgCheck` looks at the `ArgCheck` object. If it finds any errors or warnings, those are printed for the user to review. When errors are found, the function is terminated.

### Author(s)

Benjamin Nutter

### Examples

    ## Not run:
    #* This example is taken from the discussion of argument checking at
    #* http://www.r-bloggers.com/programming-with-r---checking-function-arguments/
    cylinder.volume <- function(height, radius){
      Check <- newArgCheck()
      if (missing(height)){
        addError("A value for 'height' was not provided",
                 Check)
      } else{
        if (height < 0)
          addError("'height' must be a non-negative number",
                   Check)
      }

      if (missing(height)){
        addError("A value for 'radius' was not provided",
                 Check)
      } else {
        if (radius < 0)
          addError("'radius' must be a non-negative number",
                   Check)
      }

      if (!missing(height) & !missing(radius)){
        if (height < radius)
          addWarning("When 'height' < 'radius', you have a short, awkward looking cylinder",
                     Check)
      }

      finishArgCheck(Check)

      pi * radius^2 * height
    }

    cylinder.volume()
    cylinder.volume(height = -3)
    cylinder.volume(height = 3, radius = -2)
    cylinder.volume(height = 3, radius=2)
    cylinder.volume(height = -8, radius = 4)

    ## End(Not run)

[Package ArgumentCheck version 0.10.2 Index]