0

Is there a way in R that rounds up integer numbers to the next 10? For example all values from 0 to 9 will be converted to 10. 10 of course remains 10. Then all values from 11 to 19 are converted to 20 etc. I have founded how to round up to tne nearest 10 with: round_to <- function(x, to = 10) round(x/to)*to

firmo23
  • 7,490
  • 2
  • 38
  • 114
  • 2
    what about 10.1 ? – talat Mar 07 '19 at 13:57
  • 2
    Change `round(x/to)*to` to `ceiling(x/to)*to` edit: depending on your answer to what @docendo discimus asked – Andrew Mar 07 '19 at 13:57
  • docendo only integers. I will edit. – firmo23 Mar 07 '19 at 13:58
  • 1
    @Henrik - not sure this should close as a duplicate, since this question specifies integers only. In which case we can use interger math answers here which might be more efficient that floating point math. E.g. `next_ten <- function(x) (x %/% 10L + as.logical(x %% 10)) * 10L` – dww Mar 07 '19 at 15:02
  • of course it cannot be closed as duplicate since it looks for the next and not the nearest. – firmo23 Mar 07 '19 at 15:06
  • or with integer math again, `x + ifelse(y <- x %% 10L, 10L-y, 0)` seems quite efficient – dww Mar 07 '19 at 15:15
  • @firmo23 Please read the title of the linked question: "round **up** to the nearest" – Henrik Mar 07 '19 at 16:05

1 Answers1

1

I couldn't find an actual duplicate answer on Stack Overflow, so I am posting the following formula:

next_ten <- function(x) { 10*ceiling(x/10) }
v <- c(1, 5, 10, 11, 20, 29, 30, 31)
v
next_ten(v)

[1]  1  5 10 11 20 29 30 31
[1] 10 10 10 20 20 30 30 40

This tricks works by first finding how many tens, or decimal fractions of tens, there are (ceiling(x/10)). Then, we multiply by 10, to get the effective ceiling you want.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360