4

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)?

mikldk
  • 194
  • 1
  • 4

2 Answers2

4

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)
Clemsang
  • 5,053
  • 3
  • 23
  • 41
0

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.

mrhellmann
  • 5,069
  • 11
  • 38
  • 1
    Thanks. But I need to be able to do this dynamically at check time depending on whether `available` or not. – mikldk Jan 09 '20 at 09:08