rr-markdownknitr

How do I catch errors in inline code chunk in R Markdown?


I am batch-rendering a number of Rmd files in a loop using rmarkdown::render and I need to be able to get output even for those that have errors in inline code. I can't manually edit inline code to include things like try() so some kind of kniter hook is needed.

I tried writing an inline knit_hook that would catch inline code errors but that doesn't work because the expression is evaluated before it gets passed to the hook function.

Any suggestions would be very mcuh appreciated.

Thanks!


Solution

  • I think I figured this out in the end. The trick is to set both inline and evaluate.inline hooks. Below, evaluate.inline is an edit of the default function that adds try() to the evaluation. The inline hook then tests for output class and, if it's "try-error", returns the object as.vector (without attributes):

    knitr::knit_hooks$set(
      evaluate.inline = function (code, envir = knit_global()) {
        v = try(eval(xfun::parse_only(code), envir = envir))
        knitr::knit_print(v, inline = TRUE, options = knitr::opts_chunk$get())
      },
      inline = function(x) {
      if (any(class(x) == "try-error")) {
        as.vector(x)
      } else x
    })
    

    Hope others find this useful.