I would like to automatically save the content of every chunk to a separate output file that I can then use later.
Here's my attempt:
---
title: "Testing"
output: md_document
---
```{r, setup, include=FALSE}
local({
hook_old <- knitr::knit_hooks$get("chunk")
knitr::knit_hooks$set(chunk = function(x, options) {
fc <- file(paste0(options$label, ".out"))
writeLines(x, fc)
close(fc)
hook_old(x, options)
})
})
```
```{r firstblock, collapse = TRUE}
x <- 5
x + 5
y <- 10
y + 2
```
This almost does what I want.
It produces a file called firstblock.out which looks like this:
```r
x <- 5
x + 5
```
```
## [1] 10
```
```r
y <- 10
y + 2
```
```
## [1] 12
```
That's all the information I want, but it's not formatted correctly. For example collapse = TRUE has not been applied yet. Instead, I want the formatting to look like what I get in the markdown file that is produced:
x <- 5
x + 5
## [1] 10
y <- 10
y + 2
## [1] 12
So my question is how can I adjust my hook so that I am saving the output after applying the output type formatting?
Thanks, I hadn't thought of this. But based on the R Markdown Cookbook discussion you linked, it looks like purl only extracts the code and not the code plus results of the chunk?
Anyway, the solution I posted has been working quite well for me and I haven't noticed any adverse side effects.