Bingwei Tian
Bingwei Tian

Reputation: 83

How to purl each chunks in .Rmd file to multiple .R files using Knitr

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.

Upvotes: 5

Views: 643

Answers (1)

Thomas
Thomas

Reputation: 44555

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.

Upvotes: 3

Related Questions