Examples for 'base::stopifnot'


Ensure the Truth of R Expressions

Aliases: stopifnot

Keywords: environment programming error

### ** Examples

stopifnot(1 == 1, all.equal(pi, 3.14159265), 1 < 2) # all TRUE

m <- matrix(c(1,3,3,1), 2, 2)
stopifnot(m == t(m), diag(m) == rep(1, 2)) # all(.) |=>  TRUE

op <- options(error = expression(NULL))
# "disabling stop(.)"  << Use with CARE! >>

stopifnot(length(10)) # gives an error: '1' is *not* TRUE
Error: length(10) is not TRUE
## even when   if(1) "ok"   works

stopifnot(all.equal(pi, 3.141593),  2 < 2, (1:10 < 12), "a" < "b")
Error: pi and 3.141593 are not equal:
  Mean relative difference: 1.102658e-07
## More convenient for interactive "line by line" evaluation:
stopifnot(exprs = {
  all.equal(pi, 3.1415927)
  2 < 2
  1:10 < 12
  "a" < "b"
})
Error: 2 < 2 is not TRUE
eObj <- expression(2 < 3, 3 <= 3:6, 1:10 < 2)
stopifnot(exprObject = eObj)
Error: 1:10 < 2 are not all TRUE
stopifnot(exprObject = quote(3 == 3))
stopifnot(exprObject = TRUE)


# long all.equal() error messages are abbreviated:
stopifnot(all.equal(rep(list(pi),4), list(3.1, 3.14, 3.141, 3.1415)))
Error: rep(list(pi), 4) and list(3.1, 3.14, 3.141, 3.1415) are not equal:
  Component 1: Mean relative difference: 0.01323935
  Component 2: Mean relative difference: 0.0005069574
  Component 3: Mean relative difference: 0.0001886475
  ....
# The default error message can be overridden to be more informative:
m[1,2] <- 12
stopifnot("m must be symmetric"= m == t(m))
Error: m must be symmetric
#=> Error: m must be symmetric

options(op)  # revert to previous error handler

[Package base version 4.2.3 Index]