Skip to content

Instantly share code, notes, and snippets.

@brshallo
Forked from noamross/source_rmd.R
Last active April 1, 2021 07:10
Show Gist options
  • Save brshallo/4b8c81bc1283a9c28876f38a7ad7c517 to your computer and use it in GitHub Desktop.
Save brshallo/4b8c81bc1283a9c28876f38a7ad7c517 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)
}
}
library(magrittr)
library(stringr)
library(readr)
library(purrr)
library(glue)
library(knitr)
source_rmd_chunks <- function(file, chunk_labels, skip_plots = TRUE){
temp <- tempfile(fileext=".R")
knitr::purl(file, output = temp)
text <- readr::read_file(temp)
text <- purrr::map(chunk_labels, ~stringr::str_extract(text, glue::glue("(## ----{var})(.|[:space:])*?(?=(## ----)|$)", var = .x))) %>%
stringr::str_c(collapse = "\n")
readr::write_file(text, 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