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

后端 未结 11 1939
执笔经年
执笔经年 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:15

    The round function in R assigns special meaning to the digits parameter if it is negative.

    round(x, digits = 0)

    Rounding to a negative number of digits means rounding to a power of ten, so for example round(x, digits = -2) rounds to the nearest hundred.

    This means a function like the following gets pretty close to what you are asking for.

    foo <- function(x)
    {
        round(x+5,-1)
    }
    

    The output looks like the following

    foo(4)
    [1] 10
    foo(6.1)
    [1] 10
    foo(30.1)
    [1] 40
    foo(100.1)
    [1] 110
    

提交回复
热议问题