R Projects For Dummies
Book image
Explore Book Buy On Amazon

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(is.na(x)) ) 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.

About This Article

This article can be found in the category: