Evaluate and echo different lines

For demonstration purposes, we may want to show some source code in the output, but really evaluate different code in the background.

library(knitr)
hook_source = knit_hooks$get('source')
knit_hooks$set(source = function(x, options) {
  res = hook_source(x, options)
  if (!any(grepl("#'#' ", x))) return(res)
  gsub("(^|\n)#'#' ", '\\1', res)
})

The trick is to mask the source code in special comments (e.g. #'#'), and remove the comment markers later. Of course, you have to guarantee these markers are unique.

x=2
#'#' 1/sqrt(2 * pi) * exp(-x^2/2)
dnorm(x)

We used echo=-3 to remove the 3rd expression from the source code, and gsub() to strip #'#' off.

This is completely hack. Use with care.



Try the parsermd package in your browser

Any scripts or data that you put into this service are public.

parsermd documentation built on May 20, 2021, 5:08 p.m.