Search code examples
rlatexsweave

R / Sweave formatting numbers with \Sexpr{} in scientific notation


I am just starting to write some documents with Sweave/R and I like the \sexpr{} command that lets one tow write numbers directly within text.

If I have a number like mus=0.0002433121, well I can say round it to a number of decimal places e.g.

\Sexpr{round(mus,7)}

How to write it in the scientific notation i.e. as LaTeX would be outputting

2.43 \times 10^{-4} 

and can we control the number of significant digits to be outputted like 3 in this example?

I note that a number like sigma = 2000000 is written automatically to 2e + 06 if I specify

\Sexpr{round(sigma,2)}. 

I would prefer that it would be written as

2 \times 10^6 

same as we would get in LaTeX notation and perhaps giving us the possibility to control the number of significant digits as well.

How to achieve this?


Solution

  • I think this function should work:

    sn <- function(x,digits)
    {
      if (x==0) return("0")
      ord <- floor(log(abs(x),10))
      x <- x / 10^ord
      if (!missing(digits)) x <- format(x,digits=digits)
      if (ord==0) return(as.character(x))
      return(paste(x,"\\\\times 10^{",ord,"}",sep=""))
    }
    

    Some tests:

    > sn(2000000)
    [1] "2\\\\times 10^{6}"
    > sn(0.001)
    [1] "1\\\\times 10^{-3}"
    > sn(0.00005)
    [1] "5\\\\times 10^{-5}"
    > sn(10.1203)
    [1] "1.01203\\\\times 10^{1}"
    > sn(-0.00013)
    [1] "-1.3\\\\times 10^{-4}"
    > sn(0)
    [1] "0"
    

    If you want the result in math mode you could enter $ signs in the paste() call.

    Edit:

    Here is a Sweave example:

    \documentclass{article}
    
    \begin{document}
    <<echo=FALSE>>= 
    sn <- function(x,digits)
    {
      if (x==0) return("0")
      ord <- floor(log(abs(x),10))
      x <- x / 10^ord
      if (!missing(digits)) x <- format(x,digits=digits)
      if (ord==0) return(as.character(x))
      return(paste(x,"\\\\times 10^{",ord,"}",sep=""))
    }
    @
    
    Blablabla this is a pretty formatted number $\Sexpr{sn(0.00134,2)}$.
    
    \end{document}