Example of breaking code in Rmarkdown, not breaking report

I want to make a presentation in which I demo which error messages are show when you run invalid R code. Printing the code and the error message. However, this will obviously break the Markdown report itself. Is there a setting for code chunks or reports in general that prints the error message instead of breaking the knitting of the report.

Here is a small reprex of something that should print the error instead of breaking the report:

Adding a character to a numeric yields the following error:

x <- 2
 x + "4"

What I would do is to set your chunk to eval = FALSE and then add another chunk with one of the two variants on the same theme:

### first with purrr
x <- 2

unsafe <- function(x) {
  x + "4"
safe <- purrr::safely(unsafe)
res <- purrr::map(c(2), safe)
#> [1] "non-numeric argument to binary operator"

### second with base R
res <- tryCatch({x + "4"}, error = function(e) e)
#> [1] "non-numeric argument to binary operator"

Created on 2018-04-18 by the reprex package (v0.2.0).


You can set the chunk option error = TRUE.


Perfect! Thought there must be something like that. Cheers.

1 Like