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

后端 未结 1 632
时光取名叫无心
时光取名叫无心 2021-01-03 09:03

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.

相关标签:
1条回答
  • 2021-01-03 09:47

    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.

    0 讨论(0)
提交回复
热议问题