如何使用Knitr将.Rmd文件中的每个块分解为多个.R文件 [英] How to purl each chunks in .Rmd file to multiple .R files using Knitr
问题描述
我们可以将.Rmd文件分解为.R文件,但是如何将.Rmd文件中的每个数据块分解为以块标记命名的.R文件.
We can purl a .Rmd file to a .R file, But how to purl each chunks in .Rmd file to separate .R files named by the tag of chunk.
推荐答案
假定您有以下名为"test.Rmd"的.Rmd文档:
Assume you have the following .Rmd document called "test.Rmd":
This is a test.
```{r chunk1}
1:4
```
This is a further test.
```{r chunk2}
5:6
```
如果purl
-ed,您将获得以下信息:
If purl
-ed, you get the following:
## ----chunk1--------------------------------------------------------------
1:4
## ----chunk2--------------------------------------------------------------
5:6
您可以将其放置在单独的文件中,方法是先使用purl
,使用read_chunk
函数,然后将每个块都写入单独的文件中:
You can put this instead into separate files by first using purl
, using the read_chunk
function, and then just writing each chunk to a separate file:
library("knitr")
p <- purl("test.Rmd")
read_chunk(p)
chunks <- knitr:::knit_code$get()
invisible(mapply(function(chunk, name) {
writeLines(c(paste0("## ----",name,"----"), chunk), paste0("chunk-",name,".R"))
}, chunks, names(chunks)))
unlink(p) # delete the original purl script
knitr:::knit_code$restore() # remove chunks from current knitr session
这将为每个名为"chunk-chunk1.R"
,"chunk-chunk2.R"
等的块生成一个文件,仅包含该块的代码.
This produces a file for each chunk that is named "chunk-chunk1.R"
, "chunk-chunk2.R"
, etc. containing just the code for that chunk.
这篇关于如何使用Knitr将.Rmd文件中的每个块分解为多个.R文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!