39

I was writing an Rmarkdown document (compile to HTML) in RStudio, and there are some code chunks that deliberately generate errors. for example:

```{r}
sum(a)
```

Since there is no previous definition for a this chunk will naturally generate an error message like object 'a' not found. I'd like this error message displayed in the final HTML file, but when I press Ctrl+Shift+K in RStudio to "Knit HTML", the compiler reported the error and stopped knitting.

So how can I tell knitr to ignore such error at compiling time and display it in the knitted HTML document?

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
Benny
  • 847
  • 1
  • 10
  • 14

1 Answers1

65

Use error=TRUE to continue in case of errors: from the description of knitr chunk options,

error: (TRUE; logical) whether to preserve errors (from stop()); by default, the evaluation will not stop even in case of errors!! if we want R to stop on errors, we need to set this option to FALSE

rmarkdown::render, the function behind RStudio's "Knit HTML" button/Ctrl-Shift-K shortcut, sets error=FALSE by default (in contrast to knitr::knit, which defaults to error=TRUE)

```{r error=TRUE}
sum(a)
```
jan-glx
  • 7,611
  • 2
  • 43
  • 63
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
  • 1
    Thanks Ben! I was reading the r markdown reference guide pdf instead of the knitr website, and I guess its description of `error` needs to be updated. The similar wording in the pdf file makes me think that the behaviour of `error` option is just like that of `message` and `warning`. – Benny Dec 15 '15 at 02:48
  • I added this to the top of my RStudio script: `#+ setup, error=TRUE` – Jeffrey Girard May 01 '17 at 19:32
  • 1
    I can never remember if I need `error=TRUE` or `FALSE`. ChatGPT suggested to think of `error=TRUE` as "errors are okay" or **"it's `TRUE` that we can have errors"**. Lets see if that sticks... – jan-glx Jun 30 '23 at 06:50