Question

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

Was it helpful?

Solution

stopifnot()

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

OTHER TIPS

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

This can be achieved with the stop command. This command will halt the execution of a function and print the error message. For example, we can test if the variable something is FALSE:

if(something == FALSE){
   stop("error message to print")   
}

Similarly, the warning command will print a warning (but continue executing the code).

if(something == FALSE){
   warning("error message to print")   
}

These are both provided by base R and require no packages to run or include in writing your own functions. I prefer this approach to write code with fewer dependancies and this syntax is widely used in package development. However, similar functionality is supported by the "assertthat" package with the assert_that function that has recently been released as part of Hadley's "tidyverse".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top