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

后端 未结 2 1377
暗喜
暗喜 2021-02-04 07:23

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.

2条回答
  •  难免孤独
    2021-02-04 07:30

    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}
    <>= 
    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}
    

提交回复
热议问题