[R] capturing errors in Sweave

Berwin A Turlach berwin at maths.uwa.edu.au
Tue Mar 2 09:57:33 CET 2010


G'day Sundar,

On Mon, 1 Mar 2010 23:46:55 -0800
Sundar Dorai-Raj <sdorairaj at gmail.com> wrote:

> Thanks for the input, but I don't want "try" in the Sweave output. I
> want the output to look just like it does in the console, as if an
> uncaptured error really did occur.

I don't think that you will get around using "try"; and you will have
to work moderately hard to make the output appear as it does on the
console.  Probably somewhere along the lines:

++++++++++++++++++++ Sweave code start ++++++++++++++++++++++++++
<<Function-4a>>=
MySqrt <- function(x) {
  if (missing(x)) {
    stop("'x' is missing with no default")
  }
  if (!is.numeric(x)) {
    stop("'x' should only be numeric")
  }
  if (x < 0) {
    stop("'x' should be non-negative")
  }
  return(sqrt(x))
}
@

<<echo=FALSE>>=
tmp <- try(MySqrt())
@ 
<<eval=FALSE>>=
MySqrt()    
@ 
<<echo=FALSE>>=
  cat(tmp[1])
@ 

<<echo=FALSE>>=
tmp <- try(MySqrt("a"))
@ 
<<eval=FALSE>>=
MySqrt("a")
@ 
<<echo=FALSE>>=
  cat(tmp[1])
@ 

<<echo=FALSE>>=
tmp <- try(MySqrt(-2))
@ 
<<eval=FALSE>>=
MySqrt(-2)  
@ 
<<echo=FALSE>>=
  cat(tmp[1])
@ 

<<>>=
MySqrt(4)
@ 
+++++++++++++++ Sweave code end ++++++++++++++++++++++++++++++++++

Now what I would like to know is how to include easily warning messages
in my Sweave output without having to try whether Jean Lobry's [1] hack
still works. :)

HTH.

Cheers,

	Berwin

[1] https://www.stat.math.ethz.ch/pipermail/r-help/2006-December/121975.html

========================== Full address ============================
Berwin A Turlach                      Tel.: +61 (8) 6488 3338 (secr)
School of Maths and Stats (M019)            +61 (8) 6488 3383 (self)
The University of Western Australia   FAX : +61 (8) 6488 1028
35 Stirling Highway                   
Crawley WA 6009                e-mail: berwin at maths.uwa.edu.au
Australia                        http://www.maths.uwa.edu.au/~berwin



More information about the R-help mailing list