tags:

views:

102

answers:

3

I'm writing some R notes with Sweave and would like to show common errors. For example,

<<echo=TRUE, eval=TRUE>>=
x = 5
#Case matters!
x*X
@

However when sweaving, the document won't compile due to the R error. Is there any way to make sweave compile and show the (nicely formated) error?

+1  A: 

Wrap your error in a try() command. Then it will keep running:

> {print(1); try(x*X); print(2)}
[1] 1
Error in try(x * X) : object 'X' not found
[1] 2
Shane
I thought of that, but would like to avoid displaying 'try'
csgillespie
My other thought was that there might be an options(error=some.function) that could work, but I can't find anything. You could call each piece of code twice: once with a try and echo=FALSE but eval=TRUE and capture the error message. Then once without the try and the settings reversed. Then just print out the error message separately.
Shane
+1  A: 

As Shane suggests, use

<<echo=TRUE,eval=FALSE>> 

for the code that will error, but you want to display, and then again with

<<echo=FALSE,eval=TRUE,results=verbatim>> 

but with the same code wrapped in a try.

There's an example here: http://tolstoy.newcastle.edu.au/R/help/05/09/11690.html

mdsumner