Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of "throw" in R

People also ask

How do I throw an exception in R?

Throws an exception by calling stop(). Note that throw() can be defined for specific classes, which can then be caught (or not) using tryCatch (). This default function will be overridden by ditto in the R.

How do I investigate an error in R?

You can use traceback() to locate where the last error occurred. Usually it will point you to a call you make in your function. Then I typically put browser() at that point, run the function again and see what is going wrong. The number means how deep we are in the nested functions.

Where can I find errors in R?

Use traceback() to determine where a given error is occurring. Output diagnostic information in code with print() , cat() or message() statements. Use debug() to automatically open a debugger at the start of a function call. Use trace() to start a debugger at a location inside a function.


See help(tryCatch):

Conditions are signaled by 'signalCondition'. In addition, the
'stop' and 'warning' functions have been modified to also accept
condition arguments.

and later under 'See Also':

'stop' and 'warning' signal conditions, and 'try' is essentially a simplified version of 'tryCatch'.

so you probably want stop.


Simple example:

f <- function(a, b){ 

    if (a == 0){ 
            stop("error message")
    }
 }

Beyond the base functions that Dirk mentions:

The R.oo package has additional exception handling functionality, including a throw() function which is very useful. You can catch exceptions with the usual try or trycatch functions:

> try(throw("Division by zero.")); print("It's ok!");
Error: [2009-10-22 10:24:07] Exception: Division by zero.
[1] "It's ok!"

You can read more about it here: http://www1.maths.lth.se/help/R/R.oo/


Actually the function stopifnot is very convenient to implement sanity checks in your code. It takes in several logical expressions and returns an error if any of them evaluates to false.

Example: To check if column 'c' exists in the dataframe 'df':

df <- data.frame(a = numeric(), b = numeric())
stopifnot(!is.null(df$c))

This will throw the following error:

Error: !is.null(df$c) is not TRUE

You can check if the column exists and do whatever your want.
Suppose a data.frame named df1 and checking if column col1 exists:

if(! any(grepl('^col1$',colnames(df1)))) stop("nonexistent column")

or

if(! any(grepl('^col1$',colnames(df1)))) return(-1)

For instance