# Knitr and numbers

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.

Then

\documentclass{article}

\begin{document}

Integer:
\Sexpr{14}

Double:
\Sexpr{-1.2324234}

\end{document}


will be knitted as

\documentclass{article}

\begin{document}

Integer:
14

Double:
\ensuremath{-1.2324}

\end{document}


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
{-1.2324}
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{}?

• 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 '14 at 1:31