1
votes

I found out that the "options" function in R doesn't persist through the chunks.

To be specific, I first write down a chunk like

options(digits = 15)

and then write down a separate chunk like

a = 1/2^10
a

But the 'digits' option I had set in the previous chunk doesn't work at all and goes back to the default.

I found out that the "options" function works in the specific chunk that it's in, but it is annoying to write down these options in every single chunks.

Is there any way to fix this? Any help is appreciated!

1

1 Answers

0
votes

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

enter image description here

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.