Save knitr chunk to R file

試著忘記壹切 提交于 2019-12-10 09:31:39

问题


In knitr there is a read_chunk function which read external code into a chunk. Is it possible to reverse the process. That is, make a function write_chunk() which save the source code in the chunk to an R file? The file name may the same as the chunk name.


回答1:


I found a solution using hooks. Add the following hook:

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

and use option <<chunk-name, write_chunk=TRUE>> in the header of a chunk.




回答2:


You can use the following syntax

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

But this I can prove the following error:

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

Adding the following parameter (encoding = "UTF-8"), the coding problem is solved

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


来源:https://stackoverflow.com/questions/33418505/save-knitr-chunk-to-r-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!