Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
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
by

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

Description

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.

Usage

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

Arguments

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

{

   expr1

   expr2

   ....

}

local

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

 {

   print(i)

   stopifnot(less_than_5(i))

 }

[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
2 answers

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...