Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transforming numbers in R

Tags:

r

I have a specific need to "transform" a number in R. As an example,

A "floor" operation behave as:

138  -> 100
1233 -> 1000

A "ceiling" operation behave as:

138  -> 200
1233 -> 2000

Is there an easy way to accomplish this in R? thanks

like image 209
python152 Avatar asked May 09 '13 14:05

python152


1 Answers

You could extract the 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 and integrate old ex function (ex <- function(x)floor(log10(x))) to speedup the calculation a little bit
  • add benchmark to compare against @eddi's floorR

benchmark:

## provided by @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
like image 159
sgibb Avatar answered Nov 15 '22 23:11

sgibb