Does R have an assert statement as in python?

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


Solution 1:

stopifnot()

You may also be interested in packages like Runit and testthat for unit testing.

Solution 2:

@Nick:

You can control your error message if you write a function with a descriptive name to test the condition that will throw an error in your program. Here's an example:

Less_Than_8 = function(x) return(x < 8)

for (i in 1:10)
{
  print(i)
  stopifnot(Less_Than_8(i))
}

This will print the numbers 1 through 8, then print a message that says

Error: Less_Than_8(i) is not TRUE

It would be nice if the "i" in parentheses was replaced with the value that failed the test, but you get what you pay for.

If you need anything fancier than that, look into Runit and testthat as Harlan suggested.