4
votes

I have many chunks in my documents some of them produce 2 plots side by side, some produce 3 plots side by side and some others are just for displaying results (among which some even echo out the code). I can set the global knitr option for the document as follows;

{r setup, include = FALSE, cache = FALSE}
    knitr::opts_chunk$set(
      comment = NA,
      fig.width = 7,
      out.width = 50%,
      warning = FALSE
    )

But I want to set up multiple sets of such global options, so that some target the figure chunks with double figure side by side and some target the result output.

Since the options are just a list, I can create multiple lists of various options, but I am wondering how can I include those options in those individual chunks?

1

1 Answers

3
votes

I'd recommend using option hooks for the job. Whenever a certain chunk option is set (i.e., is not NULL), the corresponding option hook runs and sets the desired chunk options.

The following example defines two sets of rules: "chatty" prints a prompt and a very funny symbol in front of outputs whereas "silent" suppresses the prompt and prints nothing in front of outputs.

Likewise, you could set fig.width and out.width as you wish.

```{r, echo = FALSE}
library(knitr)
opts_hooks$set(chatty = function(options) {
  options$prompt = TRUE
  options$comment = ";-)"
  return(options)
})

opts_hooks$set(silent = function(options) {
  options$promt = FALSE
  options$comment = ""
  return(options)
})
```

# Demo

## Default

```{r}
print("Default")
```

## Chatty

```{r, chatty = TRUE}
print("chatty")
```

## Silent

```{r, silent = TRUE}
print("silent")
```