Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does not R round function round big numbers

I need a R function that always returns same number of digits after the decimal point regardless of how big the argument is. I tried round() but it does not work this way. Here is my example:

Rweb:> round(111234.678912,4) # expect 111234.6789
[1] 111234.7 
Rweb:> round(111234.678912/10,4) # expect 11123.4679    
[1] 11123.47 
Rweb:> round(111234.678912/100,4) # expect 1112.3468      
[1] 1112.347 
Rweb:> round(111234.678912/1000,4)     
[1] 111.2347 
Rweb:> round(111234.678912/10000,4)     
[1] 11.1235 

It does work if the argument is in exponential format but I need work with numbers in floating format.

like image 637
rocketScientist Avatar asked Sep 19 '12 04:09

rocketScientist


Video Answer


1 Answers

It does round the number to the correct number of digits. However, R has limits on the number of digits it displays of very large numbers. That is- those digits are there, they just aren't shown.

You can see this like so:

> round(111234.678912,4)
[1] 111234.7
> round(111234.678912,4) - 111234
[1] 0.6789

You can use formatC to display it with any desired number of digits:

> n = round(111234.678912,4)
> formatC(n, format="f")
[1] "111234.6789"
> formatC(n, format="f", digits=2)
[1] "111234.68"

As @mnel helpfully points out, you can also set the number of digits shown (including those to the left of the decimal point) using options:

> options(digits=6)
> round(111234.678912,4)
[1] 111235
> options(digits=10)
> round(111234.678912,4)
[1] 111234.6789
like image 115
David Robinson Avatar answered Sep 20 '22 22:09

David Robinson