问题
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