How to source R Markdown file like `source('myfile.r')`?

Jeromy Anglim picture Jeromy Anglim · Jun 10, 2012 · Viewed 38.5k times · Source

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 the output was desired. I.e., knitr outputs the R code from myfile.rmd into myfile.R.

However, it doesn't seem perfect:

  • it results in the creation of an extra file
  • it needs to appear in its own code chunk if control over the display is required.
  • It's not as elegant as simple source(...).

Thus my question: Is there a more elegant way of sourcing the R code of an R Markdown file?

Answer

Yihui Xie picture Yihui Xie · Jun 10, 2012

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.