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

查看:20
本文介绍了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 	imes 10^{-4} 

在这个例子中,我们可以控制要输出的有效数字的数量像 3 吗?

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

我注意到,如果我指定,像 sigma = 2000000 这样的数字会自动写入 2e + 06

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

Sexpr{round(sigma,2)}. 

我希望它写成

2 	imes 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}

egin{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天全站免登陆