Write a hook to save a copy of chunk post-formatting

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?

Here's my solution:

```{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"))
    y <- hook_old(x, options)
    writeLines(y, fc)
    close(fc)
    return(y)
  })
})
```

Not sure if this is kosher, though! Any thoughts or better solutions would be appreciated!

1 Like

knitr and thus rmarkdown has a purl() feature which will allow to have a .R script from a Rmd file.

This R script will be made of all code chunks that should be purled.

See about this at :

Maybe you were looking for this ?

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.

1 Like

Oh indeed I missed this - purl is indeed only for the source code that could then be ran as an R script !

This topic was automatically closed 45 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.