[R] Rounding

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Thu Sep 19 10:25:45 CEST 2002


Ko-Kang Kevin Wang <kwan022 at stat.auckland.ac.nz> writes:

> Hi,
> 
> Suppose I have:
>   459
>   1789
>   23590
> and I'd like to round them to:
>   400
>   1700
>   24000
> 
> On the other hand, say if I have:
>   232
>   1234
>   23120
> that need to be rounded to:
>   300
>   1300
>   24000
> 
> I tried the round(), floor() or ceiling() and can't get what I want.  Is
> there any tricks I can use to achieve this goal?

Not beyond brute force...

 myroundup <- function(x,d){e<-10^(floor(log10(x)-d));ceiling(x/e)*e}
 myroundup(c(232,1234,23120),1)

Notice that there are some obnoxious cases for exact powers of 10 that
you might want to fudge with, e.g.

> myroundup(10^25,1)
[1] 1.1e+25

but that seems to be the first positive power of 10 that gets in
trouble. For negative powers it's already at

> myroundup(1e-5,1)
[1] 1.1e-05


This suggests that you might want something like

myroundup <- function(x,d){e<-10^(floor(log10(x)-d));ceiling(x/e-1e-15)*e}

but you should maybe also watch out for the anomalies in

> floor(log10(10^(0:20)))
 [1]  0  1  2  2  4  5  5  7  8  8 10 11 11 12 14 14 16 17 17 19 20

-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list