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
.
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.
" Inline " code is code that can be inserted directly into 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) .
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()
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, ...)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With