How to round up to the nearest 10 (or 100 or X)?

Viewed 111432

I am writing a function to plot data. I would like to specify a nice round number for the y-axis max that is greater than the max of the dataset.

Specifically, I would like a function foo that performs the following:

foo(4) == 5
foo(6.1) == 10 #maybe 7 would be better
foo(30.1) == 40
foo(100.1) == 110 

I have gotten as far as

foo <- function(x) ceiling(max(x)/10)*10

for rounding to the nearest 10, but this does not work for arbitrary rounding intervals.

Is there a better way to do this in R?

12 Answers

If you always want to round a number up to the nearest X, you can use the ceiling function:

#Round 354 up to the nearest 100:
> X=100
> ceiling(354/X)*X
[1] 400

#Round 47 up to the nearest 30:
> Y=30
> ceiling(47/Y)*Y
[1] 60

Similarly, if you always want to round down, use the floor function. If you want to simply round up or down to the nearest Z, use round instead.

> Z=5
> round(367.8/Z)*Z
[1] 370
> round(367.2/Z)*Z
[1] 365

I tried this without using any external library or cryptic features and it works!

Hope it helps someone.

ceil <- function(val, multiple){
  div = val/multiple
  int_div = as.integer(div)
  return (int_div * multiple + ceiling(div - int_div) * multiple)
}

> ceil(2.1, 2.2)
[1] 2.2
> ceil(3, 2.2)
[1] 4.4
> ceil(5, 10)
[1] 10
> ceil(0, 10)
[1] 0

This rounds x up to the nearest integer multiple of y when y is positive and down when y is negative:

rom=\(x,y)x+(y-x%%y)%%y
rom(8.69,.1) # 8.7
rom(8.69,-.1) # 8.6
rom(8.69,.25) # 8.75
rom(8.69,-.25) # 8.5
rom(-8.69,.25) # -8.5

This always rounds to the nearest multiple like round_any in plyr (https://github.com/hadley/plyr/blob/34188a04f0e33c4115304cbcf40e5b1c7b85fedf/R/round-any.r):

rnm=\(x,y)round(x/y)*y
rnm(8.69,.25) # 8.75
plyr::round_any(8.69,.25) # 8.75

round_any can also be given ceiling as the third argument to always round up or floor to always round down:

plyr::round_any(8.51,.25,ceiling) # 8.75
plyr::round_any(8.69,.25,floor) # 8.5
Related