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

后端 未结 11 1961
执笔经年
执笔经年 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 12:55

    You will find an upgraded version of Tommy's answer that takes into account several cases:

    • Choosing between lower or higher bound
    • Taking into account negative and zero values
    • two different nice scale in case you want the function to round differently small and big numbers. Example: 4 would be rounded at 0 while 400 would be rounded at 400.

    Below the code :

    round.up.nice <- function(x, lower_bound = TRUE, nice_small=c(0,5,10), nice_big=c(1,2,3,4,5,6,7,8,9,10)) {
      if (abs(x) > 100) {
        nice = nice_big
      } else {
        nice = nice_small
      }
      if (lower_bound == TRUE) {
        if (x > 0) {
          return(10^floor(log10(x)) * nice[[max(which(x >= 10^floor(log10(x)) * nice))[[1]]]])
        } else if (x < 0) {
          return(- 10^floor(log10(-x)) * nice[[min(which(-x <= 10^floor(log10(-x)) * nice))[[1]]]])
        } else {
          return(0)
        }
      } else {
        if (x > 0) {
          return(10^floor(log10(x)) * nice[[min(which(x <= 10^floor(log10(x)) * nice))[[1]]]])
        } else if (x < 0) {
          return(- 10^floor(log10(-x)) * nice[[max(which(-x >= 10^floor(log10(-x)) * nice))[[1]]]])
        } else {
          return(0)
        }
      }
    }
    

提交回复
热议问题