Warm tip: This article is reproduced from stackoverflow.com, please click
knitr Markdown r

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

发布于 2020-04-13 10:06:40

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:

  • it results in the creation of an extra file
  • it needs to appear in it's own code chunk if control over 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?

Questioner
Jeromy Anglim
Viewed
65
852 2015-08-19 22:17

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.