0 votes
1 view
in R Programming by (7.3k points)

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?

1 Answer

0 votes
by (25.4k points)

To round up to the nearest 10 or 100, you can use the following function:

roundUp <- function(x,to=10)


  to*(x%/%to + as.logical(x%%to))


For example:


[1]  10  10  40 110


[1] 5


[1] 14

Welcome to Intellipaat Community. Get your technical queries answered by top developers !