R/bcat_source_rmd.R

Defines functions bcat_source_rmd

Documented in bcat_source_rmd

#' Source Rmd Files
#'
#' Utility function to run all code chunks in an Rmd file.
#'
#' @param rmd character. Rmd file from which to run all code chunks.
#' @return An invisible list, as returned by \code{base::source()}, containing
#'   the value of the last evaluated expression and whether it was visible.
#' @author Saannidhya Rawat
#' @family utilities
#' @export
#' @source https://stackoverflow.com/questions/10966109/how-to-source-r-markdown-file-like-sourcemyfile-r
#'
bcat_source_rmd <- function(rmd) {

  stopifnot(is.character(rmd) && length(rmd) == 1)

  # create tmp file to store code
  .tmpfile <- tempfile(fileext = ".R")
  .con <- file(.tmpfile)
  on.exit(close(.con))

  # read in rmd and extract code from chunks
  full_rmd <- readr::read_file(rmd)
  codes <- stringr::str_match_all(string = full_rmd, pattern = "```(?s)\\{r[^{}]*\\}\\s*\\n(.*?)```")
  stopifnot(length(codes) == 1 && ncol(codes[[1]]) == 2)
  codes <- paste(codes[[1]][, 2], collapse = "\n")

  # write to tmp file and source
  writeLines(codes, .con)
  flush(.con)
  source(.tmpfile)
}

Try the Rbearcat package in your browser

Any scripts or data that you put into this service are public.

Rbearcat documentation built on March 21, 2026, 5:07 p.m.