Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
in R Programming by (7.3k points)

a statement that checks if something is true and if not prints a given error message and exits

1 Answer

0 votes

You can use the stopifnot() function from the base package as an assert statement in R.

According to R Documentation:

stopifnot {base}

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

For example:

less_than_5 = function(x) return(x < 5)

for (i in 1:10)





[1] 1

[1] 2

[1] 3

[1] 4

[1] 5

Error: less_than_5(i) is not TRUE

The above code prints the numbers 1 through 5, then throw an error message.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories