knitr - exclude chunks from `purl(…)`?

后端 未结 3 1310
死守一世寂寞
死守一世寂寞 2021-01-01 14:27

When I purl/tangle a document to extract the R chunks into a script, is there any way to:

  • exclude an arbitrary chunk (by name say)?
  • if not, exclude a
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-01 14:53

    Although this is more a trick than a solution, you can still modify the script resulting from purl with some regular expressions.

    For example with the following function (maybe there is a simpler solution for the regex) :

    dropchunks <- function(scriptname, what.to.drop){
        script <- readLines(scriptname)
        script <- do.call(paste, list(script, collapse = "\n") )
        subpattern = paste0("(", do.call(paste, list(what.to.drop, collapse="|")), ")")
        mainpattern <- paste('(?s)## @knitr ((?!## @knitr).)*?', subpattern, '.*?((?=## @knitr)|$)', sep="")
        script <- gsub(pattern = mainpattern, replacement = "", x = script, perl=TRUE)
        writeLines(text = script, con= scriptname)
    }
    

    You can then do this to remove all code chunk containing eval=F :

    library(knitr)
    purl("test.Rmd")
    dropchunks("test.R", "eval=F")
    

    You can do this to remove the chunk named "function" or "example" (and in fact it will remove any chunk that contains these words somewhere but this could be changed by changing the regex):

    purl("test.Rmd")
    dropchunks("test.R", c("function", "example"))
    

提交回复
热议问题