Skip to content


How to ignore errors in R

Sometimes in R the functions you used are designed to return a blocking error in some conditions where you wouldn’t want to actually stop. For instance, I’m using a loop to match genes to their GO functions and get the list of GO functions out of this, but some genes have no associated GO functions, and the author of the mapping function thought it would be clever to throw an error instead of simply an empty list in such a case (well, actually, sometimes it does return an empty list, and sometimes an error).

Gladly, there’s a way to bypass this, using a system close to the usual try … catch exception throwing system. R offers several functions, since in this case we don’t want to catch the exception but only to skip it I won’t use the more complete tryCatch(expr, error = function(e) e), but only the try(expr, silent = FALSE) function. Basically, the code is:

tmpInfo=try(theErrorProneFunction(param),silent=TRUE);
if(is(tmpInfo)!="try-error") {
   [do your stuff]
}

The first line runs you function. If there’s no error, it will store the function’s result in tmpInfo, otherwise tmpInfo will be a “try-error” object. Silent means the error won’t be displayed in the console. Then on the second line, all you need to do is check if tmpInfo isn’t a “try-error” object: if it is, you skip you action block (and, for instance, move on to the next iteration), otherwise, you process the result of theErrorProneFunction.

Bonus: there’s also a suppressWarnings() function for a quieter output when you use functions that throw lots of warnings.

Posted in R (R-project).


0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.



Some HTML is OK

or, reply to this post via trackback.

Sorry about the CAPTCHA that requires JS. If you really don't want to enable JS and still want to comment, you can send me your comment via e-mail and I'll post it for you.

Please solve the CAPTCHA below in order to fight spamWordPress CAPTCHA