stopifnot {base}R Documentation

Ensure the Truth of R Expressions


If any of the expressions (in ... or exprs) are not all TRUE, stop is called, producing an error message indicating the first expression which was not (all) true.


stopifnot(..., exprs, local = TRUE)


..., exprs

any number of (typically but not necessarily logical) R expressions, which should each evaluate to (a logical vector of all) TRUE. Use either ... or exprs, the latter typically an unevaluated expression of the form


(only when exprs is used:) indicates the environment in which the expressions should be evaluated; by default the one where stopifnot() has been called from.


This function is intended for use in regression tests or also argument checking of functions, in particular to make them easier to read.

stopifnot(A, B) or equivalently stopifnot(exprs= {A ; B}) are conceptually equivalent to

 { if(any( || !all(A)) stop(...);
   if(any( || !all(B)) stop(...) }

Since R version 3.5.0, expressions are evaluated sequentially, and hence evaluation stops as soon as there is a “non-TRUE”, as indicated by the above conceptual equivalence statement. Further, when such an expression signals an error or warning, its conditionCall() no longer contains the full stopifnot call, but just the erroneous expression.

Also, since R version 3.5.0, stopifnot(exprs = { ... }) can be used alternatively and may be preferable in the case of several expressions, as they are more conveniently evaluated interactively (“no extraneous , ”). At the beginning of a testing R script, it may further be useful to set the “alias”,

 assert <- function(exprs) stopifnot(exprs = exprs) 

Since R version 3.4.0, when an expression (from ...) is not true and is a call to all.equal, the error message will report the (first part of the) differences reported by all.equal(*).


(NULL if all statements in ... are TRUE.)

See Also

stop, warning; assertCondition in package tools complements stopifnot() for testing warnings and errors.


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(all.equal(pi, 3.141593),  2 < 2, all(1:10 < 12), "a" < "b")
## More convenient for interactive "line by line" evaluation:
stopifnot(exprs = {
  all.equal(pi, 3.1415927)
  2 < 2
  all(1:10 < 12)
  "a" < "b"

# long all.equal() error messages are abbreviated:
stopifnot(all.equal(rep(list(pi),4), list(3.1, 3.14, 3.141, 3.1415)))

options(op)  # revert to previous error handler

[Package base version 3.5.0 Index]