28

when displaying a number with inline-code with more than four digits like

`r 21645`

the result in a knitted html-file is this: 2.164510^{4} (in reality inside the inline-hook there is a calculation going on which results in 21645). Even though I just want it to print the number, like so: 21645. I can easily fix this for one instance wrapping it inside as.integer or format or print, but how do I set an option for the whole knitr-document so that it prints whole integers as such (all I need is to print 5 digits)? Doing this by hand gets very annoying. Setting options(digits = 7) doesnt help. I am guessing I would have to set some chunk-optionor define a hook, but I have no idea how

grrgrrbla
  • 2,529
  • 2
  • 16
  • 29
  • potential duplicate of http://stackoverflow.com/questions/25946047/how-to-prevent-scientific-notation-in-r (linked to in other answer) – michael Jul 20 '16 at 06:16

3 Answers3

33

I already solved it, just including the following line of code inside the setoptions-chunk in the beginning of a knitr document:

options(scipen=999)

resolves the issue, like one can read inside this answer from @Paul Hiemstra:

https://stackoverflow.com/a/25947542/4061993

from the documentation of ?options:

scipen: integer. A penalty to be applied when deciding to print numeric values in fixed or exponential notation. Positive values bias towards fixed and negative towards scientific notation: fixed notation will be preferred unless it is more than scipen digits wider.

Community
  • 1
  • 1
grrgrrbla
  • 2,529
  • 2
  • 16
  • 29
24

If you don't want to display scientific notation in this instance, but also don't want to disable it completely for your knitr report, you can use format() and set scientific=FALSE:

`r format(21645, scientific=FALSE)`
Megatron
  • 15,909
  • 12
  • 89
  • 97
10

Note that if you type your numeric as integer it will be well formatted:

`r 21645L`

Of course you can always set an inline hook for more flexibility( even it is better to set globally options as in your answer):

```{r}
inline_hook <- function(x) {
  if (is.numeric(x)) {
    format(x, digits = 2)
  } else x
}
knitr::knit_hooks$set(inline = inline_hook)

```
Yihui Xie
  • 28,913
  • 23
  • 193
  • 419
agstudy
  • 119,832
  • 17
  • 199
  • 261
  • The first part of your answer I knew, the second part about the hook is interesing, I didnt unterstand how a hook works, now I know, thanks alot! If I understand this correctly the hook only affects how numeric-vectors are displayed and nothing else? – grrgrrbla Jun 17 '15 at 10:51