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.
Asked
Active
Viewed 287 times
2 Answers
4
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.

Relund
- 611
- 3
- 14
0
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")

rral
- 554
- 3
- 20
-
This is not want I want. I only want to save the source code from a single chunk. Moreover, the function must work inside the Rnw, so you can e.g. apply a function on the saved R file in the next chunk. – Relund Oct 29 '15 at 16:03