tags:

views:

267

answers:

2

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.

+5  A: 

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.

Dirk Eddelbuettel
That works perfectly. R is so weird, through no fault of their own -- it was designed long before we ironed out good interpreted language design.
ws
+1  A: 

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/

Shane
Hehe. R isn't funky enough without OO? Sorry to be flip, and definitely thanks for the interesting answer, but I will go with plain old stop() above.
ws