Last active
December 13, 2023 18:52
-
-
Save noamross/a549ee50e8a4fd68b8b1 to your computer and use it in GitHub Desktop.
Source an RMD file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#' 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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 incallr::r()
which I describe here: https://stackoverflow.com/a/71119357/9059865