Jenny Bryan
29 September, 2014
Context: In a recent lesson, I claim (with some justification) that raising an error inside a function via if() ... stop()
often gives more info than using stopifnot()
. This is partly because you get to write your own error message. But also because you learn the name of the function that threw the error. Or so I thought.
Here's a toy function to generate an error.
my_fun <- function(x) {
if(x < 0) {
stop("x must be non-negative!")
}
x
}
When I call this function interactively, the error message names my_fun
specifically:
> my_fun(-3)
Error in my_fun(-3) : x must be non-negative!
But when executed in a chunk of a rendered R Markdown file, that info about the error-generating function is lost:
my_fun(-3)
## Error: x must be non-negative!
Is this a non-negotiable aspect of knitting? Am I doing something wrong?
As part of my study, I put the function definition and the error-triggering call in a plain .r
file.
Here I run it using the bash engine, i.e. via system()
.
Rscript 2014-09-29_knitr-treatment-errors.r
## Error in my_fun(-3) : x must be non-negative!
## Execution halted
The guilty function IS reported above.
And here's what happen when I render()
the script.
Rscript -e 'rmarkdown::render("2014-09-29_knitr-treatment-errors.r", quiet = TRUE)'
## Quitting from lines 3-10 (2014-09-29_knitr-treatment-errors.spin.Rmd)
## Error in my_fun(-3) : x must be non-negative!
## Calls: <Anonymous> ... withCallingHandlers -> withVisible -> eval -> eval -> my_fun
## Execution halted
The guilty function IS reported above.
@jennybc
Have you tried adding
error = FALSE
to yourknitr
opts? I will allow render to continue with errors when callingrender
directly, not fromRScript
.