R/Sweave用科学记数法用\ Sexpr {}格式化数字 [英] R / Sweave formatting numbers with \Sexpr{} in scientific notation

查看:133
本文介绍了R/Sweave用科学记数法用\ Sexpr {}格式化数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用Sweave/R编写一些文档,并且我喜欢\sexpr{}命令,该命令允许一个拖曳直接在文本内写数字.

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.

如果我有一个像mus=0.0002433121这样的数字,那么我可以说四舍五入到小数点后一位,例如

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

如何以科学计数法编写它,例如,将输出LaTeX

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

2.43 \times 10^{-4} 

,在这个示例中,我们可以控制要输出的有效位数吗?例如3.

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

我注意到,如果我指定

\Sexpr{round(sigma,2)}. 

我希望将其写为

2 \times 10^6 

与我们在LaTeX表示法中得到的含义相同,也许也使我们能够控制有效数字的数量.

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

如何实现?

推荐答案

我认为此功能应该起作用:

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

一些测试:

> 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"

如果要在数学模式下获得结果,可以在paste()调用中输入$符号.

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

这是一个Sweave示例:

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}

这篇关于R/Sweave用科学记数法用\ Sexpr {}格式化数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆