Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 209
mikldk Avatar asked Oct 12 '25 02:10

mikldk


1 Answers

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)
like image 156
Clemsang Avatar answered Oct 14 '25 17:10

Clemsang