2

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

luism
  • 33
  • 6
  • 3
    I don't think that what you mean is called rounding. You could get the desired result by dividing by ten and rounding to the next integer. But coming from 1445 to 145 is not called rounding. – MrLukas Oct 10 '22 at 12:25
  • try `round(c(1445, 1526, 2474 )/10)` – Karthik S Oct 10 '22 at 12:27
  • @KarthikS, post as an answer? – Ben Bolker Oct 10 '22 at 12:28
  • @MrLukas Thanks, yes of course you're right. I tried the last half hour using the round() function ^^ – luism Oct 10 '22 at 12:28
  • 2
    But note that `round(1445/10)` gives 144, not 145. If you really want 5 to always round up (not round to even), you can't use `round()`, you use `floor(x/10 + 0.5)`. – user2554330 Oct 10 '22 at 12:31
  • @user2554330 Yes just noticed that too - using floor() worked though. Thanks – luism Oct 10 '22 at 12:33

2 Answers2

3

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
GKi
  • 37,245
  • 2
  • 26
  • 48
1

You can use round with digit = -1:

round(x + .5, digit = -1) / 10
#[1] 145 153 247
Maël
  • 45,206
  • 3
  • 29
  • 67