How to Work with Lookup Tables in R
How to Format Numbers in R
How to Look at the Structure of a Factor in R

How to Generate Your Own Error Messages in R

Generating your own messages may sound strange, but you can actually prevent bugs in R by generating your own errors. Remember the logic error in the logitpercent() function? It would’ve been easier to spot if the logit() function returned an error saying that you passed a number greater than 1.

Adding sensible error (or warning) messages to a function can help debugging future functions where you call that specific function again. It especially helps in finding semantic or logic errors that are otherwise hard to find.

How to create error messages in R

You can tell R to throw an error by inserting the stop() function anywhere in the body of the function, as in the following example:

logit <- function(x){
 if( any(x < 0 | x > 1) ) stop('x not between 0 and 1')
 log(x / (1 - x) )

With the if() statement, you test whether any value in x lies between 0 and 1. Using the any() function around the condition allows your code to work with complete vectors at once, instead of with single values. Because the log() function works vectorized as well, the whole function is now vectorized.

If you change the body of the logit() function this way and try to calculate the logit of 50% and 150% (or 0.5 and 1.5), R throws an error like the following:

> logitpercent(c('50%','150%'))
Error in logit(as.numeric(x)/100) : x not between 0 and 1

As the name implies, the execution of the code stops anytime the stop() function is actually carried out; hence, it doesn’t return a result.

How to create warning messages in R

You also could make the function generate a warning instead of an error. That way you still get the same information, but the complete function is carried out so you get a result as well.

To generate a warning, use the warning() function instead of the stop() function. So, to get the result your colleague wants, you simply change the body of the function to the following code:

 x <- ifelse(x < 0 | x > 1, NA, x )
 if( any( ) warning('x not between 0 and 1')
 log(x / (1 - x) )

If you try the function now, you get the desired result:

> logitpercent(c('50%','150%'))
[1] 0 NA
Warning message:
In logit(as.numeric(x)/100) : x not between 0 and 1

Not only does the function return NA when it should, but it also gives you a warning that can help with debugging other functions that use the logit() function somewhere in the body.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
How to Step Through Debugging an R Function
How to Extract Specific Elements from a Date in R
How to Fix Data Reading Errors in R
How to Track Data Correlations in R
How to Add Titles and Axis Labels to a Plot in R