thothal
thothal

Reputation: 20409

Modify chunk options via knit_hooks

I want to define a custom chunk hook to certain r-markdown chunks, which override certain chunk options (include and eval, basically).

Use case is that I add this chunk option to a chunk, which will hide code and output per default (include = FALSE) and evaluates the chunk only if a file exists eval = <some logic>. This works if I hardcode it (cf. to chunk export_disp_mpg_by_hand but not via a custom chunk option.

But regardless of how I try it, the options are not considered.

Code

---
title: "Chunks Options"
author: "Me"
output: html_document
---

```{r setup, include = FALSE, message = FALSE}
library(ggplot2)
library(knitr)
library(here)

image_path <- "figs"
if (!dir.exists(here(image_path))) {
  dir.create(here(image_path))
}

knit_hooks$set(export_fig = function(before, options, envir) {
  if (before) {
    fn <- gsub("^export_", "", options$label)
    options$include <- FALSE
    options$eval <- !file.exists(here(image_path, paste0(fn, ".png")))
    ### Does not work either
    ## opts_current$set(include = FALSE, 
    ##                  eval = !file.exists(here(image_path, paste0(fn, ".png"))))
  }
  options
})
```

# Plot

```{r make_plot}
(pl <- ggplot(mtcars, aes(disp, mpg)) +
   geom_point())
```

```{r export_disp_mpg, export_fig = TRUE}
ggsave(here(image_path, "disp_mpg.png"), pl)
```

```{r export_disp_mpg_by_hand, include = FALSE, eval = !file.exists(here(image_path, "disp_mpg.png"))}
ggsave(here(image_path, "disp_mpg.png"), pl + geom_smooth(method = "lm"))
```

Expected Behaviour

Chunk export_disp_mpg should never be shown in the rendered output and the the file it creates should only be created if it is not existing.

Upvotes: 2

Views: 69

Answers (1)

thothal
thothal

Reputation: 20409

So close, I found the solution. In case anybody is interested, I leave the question here with the follwong working answer.

Instead of using knit_hooks, one should use opts_hooks:

```{r setup, include = FALSE}
opts_hooks$set(export_fig = function(options) {
  fn <- gsub("^export_", "", options$label)
  options$include <- FALSE
  options$eval <- !file.exists(here(image_path, paste0(fn, ".png")))
  options
})
```

Upvotes: 1

Related Questions