Equivalent of "throw" in R

RError Handling

R Problem Overview


How does one "throw" an error in R? I have a function that takes a data frame and some column names and does stuff with them. If the columns don't exist, I want the function to stop and to stop all functions depending on it.

I have looked at recover and browse and traceback but, well, they seemed to be close but not what I am looking for.

R Solutions


Solution 1 - R

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.

Solution 2 - R

Simple example:

f <- function(a, b){ 
  
    if (a == 0){ 
            stop("error message")
    }
 }

Solution 3 - R

Beyond the base functions that Dirk mentions:

The http://cran.r-project.org/web/packages/R.oo/index.html">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/

Solution 4 - R

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

Solution 5 - R

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionforkandwaitView Question on Stackoverflow
Solution 1 - RDirk EddelbuettelView Answer on Stackoverflow
Solution 2 - RChristian Herrera JiménezView Answer on Stackoverflow
Solution 3 - RShaneView Answer on Stackoverflow
Solution 4 - RChrisView Answer on Stackoverflow
Solution 5 - Rxm1View Answer on Stackoverflow