mikldk
mikldk

Reputation: 194

Can I avoid evaluating inline Rmarkdown `r code` chunks?

In a vignette demonstrating how to use a Suggested package, I have something like this:

if (suggested_package_not_available) {
  knitr::opts_chunk$set(eval = FALSE)
}

This means that the vignette still runs etc. although the Suggested package is not available. It just shows the code, not the results.

Can I do something similar for inline R code (`r code`)?

Maybe a hook that uses a regex (a la `r [^`]+`) to add two backticks around the inline code so that the inline code is showed instead of evaluated (which would normally cause an error because the chunks are no longer evaluated)?

Upvotes: 4

Views: 1155

Answers (2)

mrhellmann
mrhellmann

Reputation: 5559

It looks like double backticks before and after as well as breaking the line just after `r will work.

A more thorough explanation at yihui's site: https://yihui.org/knitr/faq/ (#7)

For inline R code, you may use the function knitr::inline_expr() (available in knitr >= v1.8). If you are writing an R Markdown document, you can use a trick: break the line right after `r (no spaces after it), and wrap the whole inline expression in a pair of double backticks, e.g.,

This will show a verbatim inline R expression `r 1+1` in the output.

Upvotes: 1

Clemsang
Clemsang

Reputation: 5491

A trick might be to print a string or evaluate the expression:

check_code <- function(expr, available){
  if(available){
    eval(parse(text = expr))
  } else {
    expr
  }
}
check_code("1+1", TRUE)
check_code("1+1", FALSE)

Upvotes: 4

Related Questions