23

I want all the numbers on my knitr report to be formatted as such by default:

format(num, digits = 2, big.mark = " ", decimal.mark = ",")

Defaulting the number of digits to 2 and the decimal mark to comma is easy, I just need to set options(digits = 2, OutDec = ",") in my first R chunk. However, I don't see how I can set the thousand separator to " " (or anything else, for that matter) in that format. I've also tried tweaking opts_chunk, but can't get it to work.

Of course, I'm trying to avoid having to insert format() inside every output, inline or otherwise. More intelligent formatting is one thing that drove me towards knitr from Sweave, after all.

How can I set default thousand separator marks on knitr?

3
  • 2
    This seems to be the answer: groups.google.com/forum/#!msg/knitr/CnFwvk1Qn1E/WY-Xhf7Ph3AJ I haven't started using knitr yet, myself.
    – Frank
    Commented Sep 23, 2013 at 19:19
  • @agstudy good one, duly edited. Commented Sep 23, 2013 at 19:45
  • @Frank, that seems to solve the problem, although it's been giving me some weird results regarding rounding numbers. I'll see about tweaking it a little, thanks. Commented Sep 23, 2013 at 19:50

1 Answer 1

33

As Frank noted, setting a knitr hook such as the following solves the problem:

knit_hooks$set(inline = function(x) {
  prettyNum(x, big.mark=" ")
})

It turns out knitr hooks are a great way to tweak the output of R chunks on knitr. It's really worth it to take a look at http://yihui.name/knitr/hooks.

Source: https://groups.google.com/forum/#!msg/knitr/CnFwvk1Qn1E/WY-Xhf7Ph3AJ

4
  • 2
    Is there a working example how to embed the knit hook in the output?
    – Seen
    Commented Mar 27, 2015 at 15:32
  • 1
    how can I do the same (simple) hook for plot markings?
    – d8aninja
    Commented May 7, 2015 at 19:03
  • 1
    And for embedded tables? Commented Apr 20, 2016 at 13:33
  • 12
    It's worth noting that this function expects the output of all inline code to be numeric, which may not be the case in an Rmarkdown document. Non-numeric inline output will then cause the document to fail to compile. One can get around this by adapting the function slightly: knitr::knit_hooks$set(inline = function(x) { if(!is.numeric(x)){ x }else{ prettyNum(round(x,2), big.mark=",") } })
    – r.bot
    Commented Apr 29, 2016 at 14:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.