GegznaV
GegznaV

Reputation: 5580

knitr: how to get and override chunk options from inside a chunk

I have 2 questions about knitr chunk options:

1) Is it possible to override knitr chunk options from inside a chunk of code so that the options were applied in the same chunk? e.g. write something like the following lines and get result as-is:

```{r, results= "markup"}
    knitr::opts_chunk$set(results= "asis")
    for (i in 1:5)
        print("# This text should be printed 'as-is'")
```

p.s. I'm familiar with knitr::asis_output.

2) Is it possible to get chunk options from inside a chunk? E.g., to use code like:

```{r}
   knitr::opts_chunk$get("results")
```

And get string markup.

```{r, results='asis'}
   knitr::opts_chunk$get("results")
```

And get string asis.

Unfortunately, knitr::opts_chunk$get("results") gets global options, and not the ones of a current chunk.

Upvotes: 2

Views: 1050

Answers (1)

RLesur
RLesur

Reputation: 5910

1) Printings can be customized using functions knitr::normal_print and knitr::asis_output (as you mentionned). For instance :

```{r, results='markup'}
knitr::asis_output(replicate(5, "# This text should be printed 'as-is'\n"))

print("# This text should be printed 'normal'")
```

and alternatively

```{r, results='asis'}
for (i in 1:5)
    cat("# This text should be printed 'as-is'\n")

knitr::normal_print("# This text should be printed 'normal'\n")
```

2) Current chunk options can be retrieved using knitr::opts_current$get(). Use :

```{r, results='asis'}
knitr::opts_current$get("results")
```

and get string asis

Upvotes: 5

Related Questions