stopifnotMsg: Check multiple conditions and return coresponding error...

Description Usage Arguments Value Author(s) Examples

View source: R/stopifnotMsg.R

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

1
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.

Author(s)

Landon Sego

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# 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")

## End(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)

## End(Not run)

Smisc documentation built on May 2, 2019, 2:46 a.m.