Source code from an Rmd file in another Rmd

I am trying to make my code more modular: loading and clearing data in one script, analysis in another, etc. If I used R scripts, it would just call sourceon data_setup.Rinside analysis.R, but I would like to document the decisions that I make in the Rmarkdown document to configure and analyze the data. So I'm trying to write some kind of function source_rmdthat will allow me to pass code from data_setup.Rmdto analysis.Rmd.

What I have tried so far:

Reply to How to fix a R Markdown file such as `source ('myfile.r')`? does not work if there are duplicate block names (problem, because the piece with the name setuphas a special behavior in Rstudio notebook processing). How to combine two RMarkdown (.Rmd) files into one output? wants to combine whole documents, not just code from one, and also requires unique block names. I tried using knit_expand, as recommended in Creating Dynamic R Markdown Blocks , but I have to name the pieces with variables in double braces, and I really like the way to make it easy for my collectors to use as well. And using knit_childas recommended inHow to make jersey calls to fix duplicate block label errors? still giving me duplicate label errors.

+4
source share
1 answer

After further searching, I found a solution. Knitr has a package option that can be changed to change the behavior for processing repeating fragments by adding a number after the label, rather than with an error. See https://github.com/yihui/knitr/issues/957 .

To set this parameter, use options(knitr.duplicate.label = 'allow').

To complete the complete code for the function I wrote,

source_rmd <- function(file, local = FALSE, ...){
  options(knitr.duplicate.label = 'allow')

  tempR <- tempfile(tmpdir = ".", fileext = ".R")
  on.exit(unlink(tempR))
  knitr::purl(file, output=tempR, quiet = TRUE)

  envir <- globalenv()
  source(tempR, local = envir, ...)
}
+3
source

Source: https://habr.com/ru/post/1668428/


All Articles