将 knitr 块保存到 R 文件

Save knitr chunk to R file

在 knitr 中有一个 read_chunk 函数可以将外部代码读入块中。是否有可能逆转这个过程。也就是说,创建一个函数 write_chunk() 将块中的源代码保存到 R 文件中?文件名可以与块名相同。

您可以使用以下语法

Stangle(file = "Your_code.Rnw",output="Code.R"):

但是这个我可以证明以下错误:

#Error: ‘Your_code.Rnw’ is not ASCII and does not declare an encoding

加入如下参数(encoding="UTF-8"),编码问题解决

Stangle("Your_code.Rnw",output="Code.R",encoding="utf8")

我找到了一个使用钩子的解决方案。添加以下挂钩:

knit_hooks$set(write_chunk = function(before, options, envir) {
    if (before) {
      fileConn<-file(paste0("chunk_",options$label,".R") )
      writeLines(options$code, fileConn)
      close(fileConn)
    }
})

并在块的 header 中使用选项 <<chunk-name, write_chunk=TRUE>>