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

后端 未结 11 1972
执笔经年
执笔经年 2020-11-27 12:20

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.

Specif

11条回答
  •  天命终不由人
    2020-11-27 13:10

    I think your code just works great with a small modification:

    foo <- function(x, round=10) ceiling(max(x+10^-9)/round + 1/round)*round
    

    And your examples run:

    > foo(4, round=1) == 5
    [1] TRUE
    > foo(6.1) == 10            #maybe 7 would be better
    [1] TRUE
    > foo(6.1, round=1) == 7    # you got 7
    [1] TRUE
    > foo(30.1) == 40
    [1] TRUE
    > foo(100.1) == 110
    [1] TRUE
    > # ALL in one:
    > foo(c(4, 6.1, 30.1, 100))
    [1] 110
    > foo(c(4, 6.1, 30.1, 100), round=10)
    [1] 110
    > foo(c(4, 6.1, 30.1, 100), round=2.3)
    [1] 101.2
    

    I altered your function in two way:

    • added second argument (for your specified X )
    • added a small value (=1e-09, feel free to modify!) to the max(x) if you want a bigger number

提交回复
热议问题