How to Change Knitr Options Mid Chunk

How to change knitr options mid chunk

Two questions: When you want both figures to be keep, use

```{r fig.keep='all'}

Default only keeps the unique plots (because your two plots are identical, the second one is removed; see the knitr graphics manual for details).

Global chunk options are active when the next chunk(s) open:

```{r}
opts_chunk$set(fig.width=10)
```

```{r}
opts_chunk$set(fig.width=2)
# Our figure is 10 wide, not 2
plot(1:1000)
```

```{r}
# Our figure is 2 wide, not 10
opts_chunk$set(fig.width=10)
plot(1:1000)
```

How to make options persist in r markdown

You may use options in an arbitrary chunk. They will be valid until they are reset.

---
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{r test}
a = 1/2^10
a
```

foo

```{r test2}
op <- options(digits=3) ## the <- assignment stores default values
a = 1/2^10
a
```

```{r test3}
options(op) ## re-assign
a = 1/2^10
a
```

Yields

Sample Image

Note:

I use digits=3 here to demonstrate that this works. Note, that digits= option considers max. significant digits and discards trailing zeroes.

Consider this:

formatC(1/2^10, digits=15, format="f")
# [1] "0.000976562500000"

This shows that the five trailing zeroes of your calculation would be discarded. Probably this caused your confusion.

Knitr - Good pratice for formatting chunks output and creating new chunk options

Thanks to an upcoming feature of knitr 1.6 (the 'code' option) I have been able to solve this.
I've edited the first post accordingly.

How to specify global chunk option in a rmarkdown website?

You can include a child document

```{r, child="_setup.Rmd"}
```

at the beginning of each rmd file.

How to insert markdown in the middle of an knitr R code chunk?

You can use the function asis_output() in knitr to only output <br> as is. So for instance, you can do this:

```{r}
plot(1:100, 1:100)
asis_output('<br>')
plot(1:100, 1:100)
```

This is better than using the results = 'asis' option for the whole chunk because the two plots are not affected.

Note that this will also work for latex if you are knitting to pdf, but back slashes will have to be escaped. For example:

```{r}
plot(1:100, 1:100)
asis_output("\\\\newline")
plot(1:100, 1:100)
```


Related Topics



Leave a reply



Submit