I return to a question, which is few months old and then maybe not yet the best practice around.

I use the siunitx package in my documents along with knitr to compile my R chunks. As far as I understand its behaviour, knitr will output integers treating them as normal characters while double into the \ensuremath{}environment.







will be knitted as






According to the answer I got to my previous question (which is working) if I want to treat my numbers with siunitx and the \num environment I need to compile my doubles in my R chunks as characters, then \Sexpr{as.character(-1.2324234)} (or alternatively \num{\Sexpr{as.character(-1.2324234)}} if I want to leverage on siunitx) which will be knitted as -1.2324234. All good.

Yet I wonder if there's any better way to manage my output. First, sometime I am not sure whether my output will be an integer or a double; especially when my data change I might generate error throughout my code just because 1 turned 1.1. Second, the solution of wrapping everything around as.character() makes my code much heavier to read especially when I also wrap everything into num{}.

I then tried to \renewcommand{\ensuremath}{\num}, which was not the good idea I thought it was:

! Undefined control sequence.
\ensuremath ->\num 

l.61 \ensuremath
The control sequence at the end of the top line
of your error message was never \def'ed. If you have
misspelled it (e.g., `\hobx'), type `I' and the correct
spelling (e.g., `I\hbox'). Otherwise just continue,
and I'll forget about whatever was undefined.

Is there any chance to gently ask knitr to output all numeric (integer and double) wrapped into \num{}?

  • 2
    I think you can copy my_inline_hook <- knitr:::.inline.hook.tex, modify it to suit your needs (you might need to add knitr::: in front of calls to internal knitr functions), and then use knit_hooks$set(inline=my_inline_hook) ?
    – Ben Bolker
    Jul 17, 2014 at 1:31


You must log in to answer this question.

Browse other questions tagged .