在R中很好地将数字格式化为有效数字

Pau*_*yuk 25 r

我想将报表中的数字格式化为有效数字,但保持尾随重要的零并正确格式化大数字

例如,数字c(10.00001,12345,1234.5,123.45,1.2345,0.12345)到3位有效数字应该是10.0,12300,1230,123,1.23,0.123但是我用不同的方法得到了不同的结果(并且似乎没有一个通用的工作.

> numbers<-c(10.00001,12345,1234.5,123.45,1.2345,0.12345)
> for(n in seq(numbers)){
+   print(signif(numbers[n],digits=3))
+   print(format(numbers[n],digits=3))
+   print(formatC(numbers[n], digits=3,format="fg"))
+   print(formatC(numbers[n], digits=3,format="fg", flag="#"))
+   }
[1] 10
[1] "10"
[1] "  10"
[1] "10.0"
[1] 12300
[1] "12345"
[1] "12345"
[1] "12345."
[1] 1230
[1] "1234"
[1] "1234"
[1] "1234."
[1] 123
[1] "123"
[1] " 123"
[1] "123."
[1] 12.3
[1] "12.3"
[1] "12.3"
[1] "12.3"
[1] 1.23
[1] "1.23"
[1] "1.23"
[1] "1.23"
[1] 0.123
[1] "0.123"
[1] "0.123"
[1] "0.123"
Run Code Online (Sandbox Code Playgroud)

这里,signif和format围绕10.00001结果.formatC with flag ="#"正确地表示小数字而不是大数字.

有没有更好的办法 ?

Pau*_*yuk 28

对不起,我当时没有更新过这个.我的问题中的所有陈述都没有,或者是非常有效.最后我用了

print(formatC(signif(numbers[n],digits=3), digits=3,format="fg", flag="#"))
Run Code Online (Sandbox Code Playgroud)

正确应对尾随零和大数字.

  • 很高兴看到使用`formatC()`是解决方案[因为我将该函数移植到R,并且特别介绍了`format ="fg"`我自己有一些考虑因素.通常,现在,`sprintf()`通常比formatC()更受欢迎,但事实上,我没有看到通过sprintf()而不是formatC()获得解决方案的好方法.BTW:给定你的`数字',我发现使用`sapply`代替for循环`sapply(数字,函数(N)格式C(signif(N,digits = 3),digits = 3,format ="fg)很方便",flag ="#"))` (5认同)

Dir*_*tel 15

你知道prettyNum()吗和它的所有选择?

  • @Jan有一个非常新的包:[prettyunits](http://cran.r-project.org/web/packages/prettyunits/) (3认同)

hac*_*ckR 6

保罗·赫尔利的上述方法对我来说无论是正数还是负数都非常有效。下面是一些代码,它将 Paul 的解决方案修改为可以指定所需有效数字的函数。

sigfig <- function(vec, n=3){ 
### function to round values to N significant digits
# input:   vec       vector of numeric
#          n         integer is the required sigfig  
# output:  outvec    vector of numeric rounded to N sigfig

formatC(signif(vec,digits=n), digits=n,format="fg", flag="#") 

}      # end of function   sigfig
Run Code Online (Sandbox Code Playgroud)

验证其工作正常

numbers <- c(50000.01, 1000.001, 10.00001, 12345, 1234.5, 123.45, 1.2345, 0.12345, 0.0000123456, -50000.01, -1000.001,-10.00001, -12345, -1234.5, -123.45, -1.2345, -0.12345, -0.0000123456)
sigfig(numbers)   # defaults to 3
sigfig(numbers, 3)
sigfig(numbers, 1)
sigfig(numbers, 6)
Run Code Online (Sandbox Code Playgroud)


Ric*_*ron 5

更准系统的选项是options(),它只是四舍五入。如果您打算经常这样做,我建议您查看 Sweave。

> a <- 1.23456789
> options(digits=2)
> a
[1] 1.2
> options(digits=6)
> a
[1] 1.23457
Run Code Online (Sandbox Code Playgroud)


Ben*_*ley 5

如果你喜欢科学记数法

> format(2^31-1, scientific = TRUE, digits = 3)
[1] "2.15e+09"
Run Code Online (Sandbox Code Playgroud)


JMT*_*0AD 5

保罗回答的另一个修改。似乎它也留下了一个尾随小数。我正在用 gsub 删除它:

sigfig <- function(vec, digits){
  return(gsub("\\.$", "", formatC(signif(vec,digits=digits), digits=digits, format="fg", flag="#")))
}
Run Code Online (Sandbox Code Playgroud)