knitr:运行Rmarkdown文档中的所有块 [英] knitr: run all chunks in an Rmarkdown document
问题描述
我有一个.rmd文件,该文件的编织过程很好.
I have an .Rmd document which knitr process just fine.
我想运行文档中的所有块,以便我可以探索 结果出现在我的R shell中.
I would like to run all the chunks in the document, so that I can explore the results in my R shell.
在Rstudio中,有一个选项可以运行文档中的所有块, 但是我找不到在简单的R会话(在终端中打开)中达到相同效果的方法.
In Rstudio there is an option to run all the chunks in the document, but I can't find a way to achieve the same effect in a simple R session (opened in my terminal).
有没有办法做到这一点?
Is there a way to do this?
推荐答案
使用Run all chunks
等效于:
- 创建一个临时R文件
- 使用
knitr::purl
将所有R个块提取到临时文件中 - 使用
source()
运行文件 - 删除临时文件
- Create a temporary R file
- Use
knitr::purl
to extract all the R chunks into the temp file - Use
source()
to run the file - Delete the temp file
赞:
tempR <- tempfile(fileext = ".R")
library(knitr)
purl("SO-tag-package-dependencies.Rmd", output=tempR)
source(tempR)
unlink(tempR)
但是您将需要将其转换为功能.这很容易,除了必须使用sys.source
在全局环境中运行R脚本:
But you will want to turn this into a function. This is easy enough, except you have to use sys.source
to run the R script in the global environment:
runAllChunks <- function(rmd, envir=globalenv()){
tempR <- tempfile(tmpdir = ".", fileext = ".R")
on.exit(unlink(tempR))
knitr::purl(rmd, output=tempR)
sys.source(tempR, envir=envir)
}
runAllChunks("SO-tag-package-dependencies.Rmd")
这篇关于knitr:运行Rmarkdown文档中的所有块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!