Knitr and tangle code without execution

I am trying to convert a fairly critical script database interface to R markdown for documentation purposes, with the intent to then link this file to get the R code that goes into my crontab. However, I found that if I install eval=T

then knitting the file runs the code (which I don't want to show up unexpectedly) and if I install eval=F

then obfuscating the file throws out all the commented code.

Is there a safe way to create a file that gets tangled up in executable code without the risk of execution? I guess I can find / replace every time eval=F

, but that seems inelegant.

+3


source to share


1 answer


I think you can achieve this by writing a chunk function. See the source code for an example knitr::hook_purl

. Here's a quick and dirty solution:

library(knitr)
knit_hooks$set(purl = function(before, options) {
  if (before) return()
  input  = current_input()  # filename of input document
  output = paste(tools::file_path_sans_ext(input), 'R', sep = '.')
  if (knitr:::isFALSE(knitr:::.knitEnv$tangle.start)) {
    assign('tangle.start', TRUE, knitr:::.knitEnv)
    unlink(output)
  }
  cat(options$code, file = output, sep = '\n', append = TRUE)
})

      



If you customize this chunk in your document, all chunks of code will be written out regardless of the chunk eval = TRUE

or FALSE

. Note that you must put this in the first piece of code in your document.

If your input document has a simple structure (like cross-referencing links), there is an even simpler approach: you can get all the code snippets through knitr:::knit_code$get()

, and all you have to do is write all of them to an R script.

+4


source







All Articles