Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rounding

r

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?

like image 570
Abe Avatar asked Jun 23 '11 22:06

Abe


People also ask

How do you round to the nearest 100?

When rounding to the nearest hundred, look at the TENS DIGIT of the number. If that digit is 0, 1, 2, 3, or 4, you will round down to the previous hundred. If that digit is 5, 6, 7, 8, or 9, you will round up to the next hundred.


1 Answers

The plyr library has a function round_any that is pretty generic to do all kinds of rounding. For example

library(plyr) round_any(132.1, 10)               # returns 130 round_any(132.1, 10, f = ceiling)  # returns 140 round_any(132.1, 5, f = ceiling)   # returns 135 
like image 189
Ramnath Avatar answered Sep 23 '22 17:09

Ramnath