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?
In R Markdown, error = FALSE is the default, which means R should stop on error when running the code chunks.
The usual way to compile an R Markdown document is to click the Knit button as shown in Figure 2.1, and the corresponding keyboard shortcut is Ctrl + Shift + K ( Cmd + Shift + K on macOS). Under the hood, RStudio calls the function rmarkdown::render() to render the document in a new R session.
Hide source code: ```{r, echo=FALSE} 1 + 1 ``` Hide text output (you can also use `results = FALSE`): ```{r, results='hide'} print("You will not see the text output.") ``` Hide messages: ```{r, message=FALSE} message("You will not see the message.") ``` Hide warning messages: ```{r, warning=FALSE} # this will generate ...
The shortcut to interrupt a running process in R depends on the R software and the operating system you are using. However, if you are using RStudio on a Windows computer, you can usually use Esc to stop a currently executing R script. Then, we can press Esc to interrupt the loop.
Use error=TRUE
: 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) ```
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With