Skip to content

Instantly share code, notes, and snippets.

@cderv
Forked from nischalshrestha/get_raw_chunks.R
Last active July 21, 2020 07:30
Show Gist options
  • Save cderv/2a72c177af6e55bbf201a74f5ab85f54 to your computer and use it in GitHub Desktop.
Save cderv/2a72c177af6e55bbf201a74f5ab85f54 to your computer and use it in GitHub Desktop.
Raw knitr chunks (inside hook context)
# test file
sample_chunk <- "
```{r hello, testing=as.logical(1), another=1 + 1}
1 + 1
```"
file = "sample.Rmd"
writeLines(sample_chunk, con = file)
foo_hook = function(before, options, envir) {
# only run after the chunk
if (before) return()
# note: this returns raw knitr chunks in list format
# has attribute of "chunk_opts"
print(knitr::knit_code$get(options$label))
}
knitr::knit_hooks$set(testing = foo_hook)
# option hook to deactivate evaluation if testing chunk option is TRUE
knitr::opts_hooks$set(testing = function(options) {
if (isTRUE(options$testing)) options$eval = FALSE
options
})
outfile <- knitr::knit(file)
file.edit(outfile)
# delete temp md file
on.exit(unlink(outfile))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment