Mark Heckmann
Mark Heckmann

Reputation: 11431

knitr - strange behaviour for digits

I ran into some trouble concerning the number of digits printed in knitr. The number does not correspond to the settings [options('digits')]. I know that it was an issue with that about a year ago but has been resolved (https://github.com/yihui/knitr/issues/120).

```{r}
packageVersion("knitr")
options("digits")
a <- 100.101
a
as.character(a)
options(digits=4)
a
options(digits=10)
a
```

This is what I get (the same on two different machines): http://rpubs.com/markheckmann/6715 . enter image description here Something is going wrong here and I do not have a clue. Any ideas?

Upvotes: 1

Views: 894

Answers (2)

Richie Cotton
Richie Cotton

Reputation: 121077

This isn't a knitr issue; it's just how R displays digits. Try your code on its own, without knitting.

a <- 100.101
a
#[1] 100.101
as.character(a)
#[1] "100.101"
options(digits=4)
a
#[1] 100.1
options(digits=10)
a
[1] 100.101

print doesn't pad numbers with zeroes to make up the width; for that you need format.

format(a, nsmall = 10)
#[1] "100.1010000000"

Upvotes: 2

Simon O&#39;Hanlon
Simon O&#39;Hanlon

Reputation: 59970

I don't think options(digits=10) is doing what you exepct. Perhaps you meant

sprintf( "%.10f",101.101)
# [1] "101.1010000000"

Upvotes: 3

Related Questions