Transforming numbers in R -


i have specific need "transform" number in r. example,

a "floor" operation behave as:

138  -> 100 1233 -> 1000 

a "ceiling" operation behave as:

138  -> 200 1233 -> 2000 

is there easy way accomplish in r?

you extract exponent separatly:

floorex <- function(x) {   ex <- 10^trunc(log10(x))   return(trunc(x/ex)*ex) }  ceilingex <- function(x) {   ex <- 10^trunc(log10(x))   return(ceiling(x/ex)*ex) } 

examples:

floorex(123) # [1] 100  ceilingex(123) # [1] 200  ceilingex(c(123, 1234, 12345)) # [1]   200  2000 20000 

edit:

  • using trunc instead of floor , integrate old ex function (ex <- function(x)floor(log10(x))) speedup calculation little bit
  • add benchmark compare against @eddi's floorr

benchmark:

## provided @eddi floorr <- function(x) {r <- signif(x, 1); r - (r > x) * 10^trunc(log10(x))}  library("microbenchmark")  x <- 123; microbenchmark(floorex(x), floorr(x), signif(x), times=1e4) # unit: nanoseconds #        expr  min   lq median     uq    max neval #  floorex(x) 2182 2414   2521 2683.0 704190 10000 #   floorr(x) 2894 3150   3278 3505.5  22260 10000 #   signif(x)  372  472    507  556.0  10963 10000  x <- 1:1000; microbenchmark(floorex(x), floorr(x), signif(x), times=1e2) # unit: microseconds #        expr     min       lq   median       uq      max neval #  floorex(x) 100.560 101.2460 101.6945 115.6385  818.895   100 #   floorr(x) 354.848 355.4705 356.0420 375.9210 1074.582   100 #   signif(x) 114.608 115.2120 115.4695 119.1805  186.738   100 

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -