如何获取像`source('myfile.r')`这样的R Markdown文件? [英] How to source R Markdown file like `source('myfile.r')`?
问题描述
我经常有一个主要的R Markdown文件或knitr LaTeX文件,其中我source
一些其他R文件(例如,用于数据处理).但是,我认为在某些情况下,使这些源文件成为其自己的可复制文档(例如,R Markdown文件不仅包含用于数据处理的命令,而且还生成可解释数据处理的可复制文档,这将是有益的).决定).
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).
因此,我想在主R Markdown文件中使用类似source('myfile.rmd')
的命令.它将提取并获取myfile.rmd
的R代码块内的所有R代码.当然,这会引起错误.
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.
以下命令有效:
```{r message=FALSE, results='hide'}
knit('myfile.rmd', tangle=TRUE)
source('myfile.R')
```
如果需要输出,可以省略results='hide'
.也就是说,knitr将R代码从myfile.rmd
输出到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(...)
那样优雅.
- 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(...)
.
因此,我的问题是: 是否有更优雅的方式来获取R Markdown文件的R代码?
Thus my question: Is there a more elegant way of sourcing the R code of an R Markdown file?
推荐答案
似乎您正在寻找一种衬板.如何将其放入您的.Rprofile
?
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()), ...)
}
但是,我不明白您为什么要source()
Rmd文件本身中的代码.我的意思是knit()
将运行该文档中的所有代码,并且如果您提取该代码并将其分批运行,则当您knit()
该文档时,所有代码将运行两次(在您自己内部运行).这两个任务应该分开.
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.
如果您真的想运行所有代码,则RStudio使此操作相当容易:Ctrl + Shift + R
.它基本上在后台调用purl()
和source()
.
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.
这篇关于如何获取像`source('myfile.r')`这样的R Markdown文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!