How to round a whole number in R

Fio*_*ona 1 r rounding

This is a really simple question but how do I round a number in R such that I only show 2 significant figures?

E.g. 326 rounds to 330 and 4999 rounds to 5000

Thanks

Jim*_* O. 8

用数字表示小数位。

round(326, digits=-1)
[1] 330
Run Code Online (Sandbox Code Playgroud)

这里的区别signif()和round()。直接取自文档:

x2 <- pi * 100^(-1:3)
round(x2, 3)
signif(x2, 3)

[1]       0.031       3.142     314.159   31415.927 3141592.654
[1] 3.14e-02 3.14e+00 3.14e+02 3.14e+04 3.14e+06
Run Code Online (Sandbox Code Playgroud)

使用最适合您的一种。

  • 这真是太好了!我不知道您可以使用负数四舍五入到“单位”水平以上。 (3认同)

s_t*_*s_t 6

Maybe this could help:

signif(4999,2)
5000

signif(326,2)
330

signif(326232,2)
330000
Run Code Online (Sandbox Code Playgroud)

And as Jim O. pointed out, there is a difference between signif() and round(). Also in performances are different, due as pointed out by Gregor, this could be not too much useful to know but maybe interesting:

library(microbenchmark)
k <- sample(1:100000,1000000,replace=T)  
microbenchmark(
    round_ ={round(k, digits=-1)},
    signif_ ={signif(k,2)} 
)

Unit: milliseconds
    expr       min        lq      mean    median        uq      max neval
  round_  68.56366  70.22595  74.02643  71.99918  75.32761 109.5727   100
 signif_ 109.57957 111.86501 121.17458 114.13232 118.88837 495.0321   100
Run Code Online (Sandbox Code Playgroud)