[Tex/LaTex] siunitx error: “invalid-number” from R

knitrrsiunitx

I have a document in .Rnw which I use to produce a .texdocument with kntir. I have a problem with the formula \num{\Sexpr{max(degree)}} which in R console produce 12598 but after the running knitr in the .tex document becomes \num{\ensuremath{1.2598\times 10^{4}}}, which create the following error in LaTex:

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!
! siunitx error: "invalid-number"
! 
! Invalid numerical input '\protect $\relax 1.2598\times 10^{4}$'.
! 
! See the siunitx documentation for further information.
! 
! For immediate help type H <return>.
!...............................................  

l.466 ... & \num{\ensuremath{1.2598\times 10^{4}}}

I am bit puzzled since in the document I have bigger numbers which do not create any problem when compiling.

These are my /siunitx options

%Separate digits with comma (e.g. 1,000,000)
\usepackage[group-separator={,}]{siunitx}
\sisetup{
  detect-all,
  detect-inline-family=math,
  detect-inline-weight=math,
  detect-display-math=true}

Best Answer

It seems you want to format the numbers using siunitx, while knitr also tries to do that automatically. Only one of them should be used, so either you do not use \num{}, or tell knitr to output the numbers without scientific notations (this is perhaps what you prefer), e.g. \Sexpr{as.character(max(degree))}, or use other functions like format(), sprintf(), and so on, to turn the numbers to character strings, so that knitr will no longer do scientific notations.