Skip to content

Instantly share code, notes, and snippets.

@brshallo
Last active December 7, 2022 13:15
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brshallo/e963b9dca5e4e1ab12ec6348b135362e to your computer and use it in GitHub Desktop.
Save brshallo/e963b9dca5e4e1ab12ec6348b135362e to your computer and use it in GitHub Desktop.
Function for sourcing individual or multiple chunks from an RMD document
library(magrittr)
library(stringr)
library(readr)
library(purrr)
library(glue)
library(knitr)
source_rmd_chunks <- function(file, chunk_labels, skip_plots = TRUE, output_temp = FALSE){
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)
}
if(output_temp) temp
}
@brshallo
Copy link
Author

@py9mrg I wasn't really planning on it. My impression is Yihui isn't crazy about knitr::purl() so didn't know if he'd want to incorporate support for something like this...

Wouldn't hurt to open an issue though, feel free to @ me on jt.

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