Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Source code from Rmd file within another Rmd

I'm attempting to make my code more modular: data loading and cleaning in one script, analysis in another, etc. If I were using R scripts, this would be a simple matter of calling source on data_setup.R inside analysis.R, but I'd like to document the decisions I'm making in an Rmarkdown document for both data setup and analysis. So I'm trying to write some sort of source_rmd function that will allow me to source the code from data_setup.Rmd into analysis.Rmd.

What I've tried so far:

The answer to How to source R Markdown file like `source('myfile.r')`? doesn't work if there are any repeated chunk names (a problem since the chunk named setup has special behavior in Rstudio's notebook handling). How to combine two RMarkdown (.Rmd) files into a single output? wants to combine entire documents, not just the code from one, and also requires unique chunk names. I've tried using knit_expand as recommended in Generate Dynamic R Markdown Blocks, but I have to name chunks with variables in double curly-braces, and I'd really like a way to make this easy for my colaborators to use as well. And using knit_child as recommended in How to nest knit calls to fix duplicate chunk label errors? still gives me duplicate label errors.

like image 274
Empiromancer Avatar asked Jan 31 '17 16:01

Empiromancer


People also ask

Is code that can be inserted directly into a .RMD file?

" Inline " code is code that can be inserted directly into a . rmd file.

How do you add a link to a RMD file?

Hyperlinks are created using the syntax [text](link) , e.g., [RStudio](https://www.rstudio.com) . The syntax for images is similar: just add an exclamation mark, e.g., ![ alt text or image title](path/to/image) .

How do I share a markdown file in R?

To share R code like function definitions, you can put this code in an R script and import it in each file with the function source() To share common R Markdown text and code chunks, you can use child documents. To share common templates, you can use the function knitr::knit_expand()


1 Answers

After some further searching, I've found a solution. There is a package option in knitr that can be set to change the behavior for handling duplicate chunks, appending a number after their label rather than failing with an error. See https://github.com/yihui/knitr/issues/957.

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

For the sake of completeness, the full code for the function I've written is

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, ...)
}
like image 184
Empiromancer Avatar answered Oct 10 '22 18:10

Empiromancer