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.
Asked
Active
Viewed 583 times
1 Answers
3
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
```
If purl
-ed, you get the following:
## ----chunk1--------------------------------------------------------------
1:4
## ----chunk2--------------------------------------------------------------
5:6
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
This produces a file for each chunk that is named "chunk-chunk1.R"
, "chunk-chunk2.R"
, etc. containing just the code for that chunk.

Thomas
- 43,637
- 12
- 109
- 140
-
This also worked for .Rnw file and Included sub file, really nice! – Bingwei Tian Sep 14 '14 at 05:53
-
@BingweiTian If this answer worked for you, consider up voting it and marking it as accepted by clicking the "check mark" to the left of the answer. – Thomas Sep 14 '14 at 08:52
-
Thanks again for kind reminding, I have checked the **Check mark**, but still donot have enough reputation to vote up. – Bingwei Tian Sep 14 '14 at 09:12