I often have a main R Markdown file or knitr LaTeX file where I source
some other R file (e.g., for data processing). However, I was thinking that in some instances it would be beneficial to have these sourced files be their own reproducible documents (e.g., an R Markdown file that not only includes commands for data processing, but also produces a reproducible document that explains the data processing decisions).
Thus, I would like to have a command like source('myfile.rmd')
in my main R Markdown file. that would extract and source all the R code inside the R code chunks of myfile.rmd
. Of course, this gives rise to an error.
The following command works:
```{r message=FALSE, results='hide'}
knit('myfile.rmd', tangle=TRUE)
source('myfile.R')
```
where results='hide'
could be omitted if output was desired. I.e., knitr outputs the R code from myfile.rmd
into myfile.R
.
However, it doesn't seem perfect:
source(...)
.Thus my question: Is there a more elegant way of sourcing the R code of an R Markdown file?
It seems you are looking for a one-liner. How about putting this in your .Rprofile
?
ksource <- function(x, ...) {
library(knitr)
source(purl(x, output = tempfile()), ...)
}
However, I do not understand why you want to source()
the code in the Rmd file itself. I mean knit()
will run all the code in this document, and if you extract the code and run it in a chunk, all the code will be run twice when you knit()
this document (you run yourself inside yourself). The two tasks should be separate.
If you really want to run all the code, RStudio has made this fairly easy: Ctrl + Shift + R
. It basically calls purl()
and source()
behind the scene.
Hi @Yihui I think it is helpful because sometimes your analysis might be organized in small scripts, but in your report you want to have the code for the whole pipeline.
So the use case here is that you want to write all of the code and have it be heavily documented and explained, but the code is run by some other script.
@BrashEquilibrium It is a matter of using
source()
orknitr::knit()
to run the code. I know people are less familiar with the latter, butpurl()
is not reliable. You have been warned: github.com/yihui/knitr/pull/812#issuecomment-53088636@Yihui What would be the proposed alternative to 'source(purl(x,...))' in your view? How can one source multiple *.Rmd-Files, without running into an error regarding duplicate chunk labels? I'd rather not want to go back to the to-be-sourced document and knit it. I use *.Rmd for many files, that I potentially have to export and discuss with others, so it would be great to be able source multiple Rmd-Files for all steps of the analysis.