Last active
December 7, 2022 13:15
-
-
Save brshallo/e963b9dca5e4e1ab12ec6348b135362e to your computer and use it in GitHub Desktop.
Function for sourcing individual or multiple chunks from an RMD document
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
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@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.