Learn R Programming

Smisc (version 0.3.9.1)

stopifnotMsg: Check multiple conditions and return coresponding error messages

Description

A more flexible version of stopifnot that allows you to control the error message returned by each condition that doesn't test true

Usage

stopifnotMsg(..., level = 1)

Arguments

Pairs of logical conditions and error messages. See Examples.

level

Whole number indicating how far back in the call stack the error should be attributed to. level = 1 goes back to the calling function, level = 2 goes back 2 levels, etc. See examples.

Value

A call to stop with the error messages from each condition that was FALSE. If all conditions are TRUE, returns NULL.

Examples

Run this code
# NOT RUN {
# A simple function
aFunction <- function(x, a = 10, b = "text") {

  # Check the arguments of the function
  stopifnotMsg(is.numeric(x),   "'x' must be numeric",
               is.numeric(a),   "'a' must be numeric",
               a > 9,           "'a' must be 10 or more",
               is.character(b), "'b' must be character")

  return(paste(x, a, b, sep = " -- "))

}

# This should run without error
aFunction(12, a = 13, b = "new")

# }
# NOT RUN {
# This should produce an error with 3 messages:
aFunction("new", a = 7, b = 5)

# And this should produce an error with 1 message:
aFunction(33, a = "bad")
# }
# NOT RUN {
### This illustrates how the 'level' argument works

# A check function that will be called within another
check <- function(a, lev) {
  stopifnotMsg(is.numeric(a), "a must be numeric", level = lev)
}

# A function that uses the check.
f <- function(a, lev = 1) {
  check(a, lev)
  return(a + 10)
}

# }
# NOT RUN {
# Note how the error is attributed to 'check'
f("a")

# But if we change the level to 2, the error will be attributed to 'f'
f("a", lev = 2)
# }

Run the code above in your browser using DataLab