Skip to content

Instantly share code, notes, and snippets.

@noamross
Last active December 13, 2023 18:52
Show Gist options
  • Save noamross/a549ee50e8a4fd68b8b1 to your computer and use it in GitHub Desktop.
Save noamross/a549ee50e8a4fd68b8b1 to your computer and use it in GitHub Desktop.
Source an RMD file
#' Source the R code from an knitr file, optionally skipping plots
#'
#' @param file the knitr file to source
#' @param skip_plots whether to make plots. If TRUE (default) sets a null graphics device
#'
#' @return This function is called for its side effects
#' @export
source_rmd = function(file, skip_plots = TRUE) {
temp = tempfile(fileext=".R")
knitr::purl(file, output=temp)
if(skip_plots) {
old_dev = getOption('device')
options(device = function(...) {
.Call("R_GD_nullDevice", PACKAGE = "grDevices")
})
}
source(temp)
if(skip_plots) {
options(device = old_dev)
}
}
@brshallo
Copy link

One limitation is that knitr::purl() can fail if using this function in an .Rmd (due to duplicate chunk labels) -- a fix is to wrap the purl call in callr::r() which I describe here: https://stackoverflow.com/a/71119357/9059865

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment