Home > Back-end >  How do you round non double numbers in R?
How do you round non double numbers in R?

Time:10-11

I'd like to round some integer numbers in R. Of course i already know the round() method, but this only seems to work on the data type 'double' or 'float'. How can i round a normal integer without any decimal values, e.g

1445 --> 145

1526 --> 153

2474 --> 247

CodePudding user response:

You can add 5 and use %/%.

x <- c(1445L, 1526L, 2474L)
(x   5L) %/% 10L
#[1] 145 153 247

Benchmark:

x <- sample(1e5)
bench::mark(GKi =  (x   5L) %/% 10L,
            Mael = round(x   .5, digit = -1) / 10,
            user2554330 = floor(x/10   0.5)
            )
#  expression       min   median `itr/sec` mem_alloc `gc/sec` n_itr  n_gc total…¹
#  <bch:expr>  <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl> <int> <dbl> <bch:t>
#1 GKi         362.34µs 364.87µs     2463.  390.67KB     21.0  1172    10   476ms
#2 Mael          4.06ms   4.21ms      237.    1.53MB     10.6   112     5   472ms
#3 user2554330 329.37µs 335.93µs     2505.   781.3KB     46.2  1139    21   455ms

Using (x 5L) %/% 10L or floor(x/10 0.5) are currently equal fast, but %/% uses less memory.
(x 5L) %/% 10L returns an integer and floor(x/10 0.5) a numeric.

x <- 1234L
str(x)
# int 1234

str((x   5L) %/% 10L)
# int 123

str(floor(x/10   0.5))
# num 123

CodePudding user response:

You can use round with digit = -1:

round(x   .5, digit = -1) / 10
#[1] 145 153 247
  • Related