0

I am working on a plotting function and need to define where to place axis labels. In calculating the increments between each label I want to avoid labels at 142, 284, etc and would rather want them at 150, 300, etc.

However, the numbers are not always in the same range. Here is how I plan to round them using a function:

  1. between 0 and 1: round up to first decimal
  2. between 1 and 10: round up to full integer or .5
  3. between 11 and 20: round up to full integer
  4. between 21 and 100: round up to multiple of 5
  5. between 101 and 200: round up to multiple of 10
  6. between 201 and 1000: round up to multiple of 50
  7. between 1001 and 2000: round up to multiple of 100
  8. between 2001 and 10000: round up to multiple of 500

My problem lies in number 2. How do round to multiples of .5? Also, is there an alternative standard function that can be used for these kinds of labeling problems?

bumblebee
  • 1,116
  • 8
  • 20

1 Answers1

1

I would suggest using dplyr's case_when to make a set of rules like this.

library(dplyr)
my_format <- function(x) {
  case_when(
    between(x, 0,     1)     ~ ceiling(x / .1 ) * .1,
    between(x, 1,     10)    ~ ceiling(x / .5 ) * .5,
    between(x, 11,    20)    ~ ceiling(x / 1  ) * 1,
    between(x, 21,    100)   ~ ceiling(x / 5  ) * 5,
    between(x, 101,   200)   ~ ceiling(x / 10 ) * 10,
    between(x, 201,   1000)  ~ ceiling(x / 50 ) * 50,
    between(x, 1001,  2000)  ~ ceiling(x / 100) * 100,
    between(x, 2001,  10000) ~ ceiling(x / 500) * 500
  )
}

my_format(0.44)
#> [1] 0.5
my_format(4.1)
#> [1] 4.5
my_format(4.51)
#> [1] 5
my_format(11.1)
#> [1] 12
my_format(22.5)
#> [1] 25
my_format(121.1)
#> [1] 130
my_format(201.1)
#> [1] 250
my_format(1002.3)
#> [1] 1100
my_format(2001.1)
#> [1] 2500
JBGruber
  • 11,727
  • 1
  • 23
  • 45
  • Might work for current problem, now imagine this "rounding" goes all the way to billions. – zx8754 Nov 04 '19 at 09:28
  • I don't see this stated as a possibility in the question. But yes, this wouldn't work then and one would need to find a more general function. – JBGruber Nov 04 '19 at 09:32
  • But anyone who can provide a more general form is welcome to post! – JBGruber Nov 04 '19 at 12:03