1

how can i use the cut() function to create breaks that start at 0?

x <- seq(0, 102, length.out = 15)
cut(x, breaks = 10)
 [1] (-0.102,10.2] (-0.102,10.2] (10.2,20.4]   (20.4,30.6]   (20.4,30.6]   (30.6,40.8]   (40.8,51]     (40.8,51]     (51,61.2]     (61.2,71.4]   (71.4,81.6]   (71.4,81.6]  
[13] (81.6,91.8]   (91.8,102]    (91.8,102]   
Levels: (-0.102,10.2] (10.2,20.4] (20.4,30.6] (30.6,40.8] (40.8,51] (51,61.2] (61.2,71.4] (71.4,81.6] (81.6,91.8] (91.8,102]
zimia
  • 930
  • 3
  • 16
  • 3
    You can specify a range of values in breaks i.e. `cut(x, breaks = c(0, 5, 10, 20,...))` – akrun Jun 13 '22 at 15:36
  • Its part of a shiny app where I cant specify the breaks but only the number of breaks – zimia Jun 13 '22 at 15:38
  • Number of breaks will automatically calculate from the given data which you may not have a control – akrun Jun 13 '22 at 15:38
  • `hist(x, breaks = 10, plot = FALSE)$breaks`. – Rui Barradas Jun 13 '22 at 15:43
  • Why can't you specify the breaks? Maybe something like `breaks = seq(0, max(x), length.out = n_breaks)` if you want to both specify the number of breaks and that they start at 0. – Gregor Thomas Jun 13 '22 at 15:45
  • i am constrained by the structure requested by the end users of the app, so its really not up to me :( – zimia Jun 13 '22 at 15:56
  • You might look at my `{santoku}` package. It has functions to chop into a given number of intervals, e.g. `chop_equally()` and `chop_evenly()`, as well as `chop_pretty()` which uses `pretty()`. – dash2 Jun 14 '22 at 08:09

1 Answers1

2

Base function pretty outputs pretty numbers. From the documentation, my emphasis.

Compute a sequence of about n+1 equally spaced ‘round’ values which cover the range of the values in x. The values are chosen so that they are 1, 2 or 5 times a power of 10.

x <- seq(0, 102, length.out = 15)
cut(x, breaks = pretty(x, n = 10), include.lowest = TRUE)
#>  [1] [0,10]    [0,10]    (10,20]   (20,30]   (20,30]   (30,40]   (40,50]  
#>  [8] (50,60]   (50,60]   (60,70]   (70,80]   (80,90]   (80,90]   (90,100] 
#> [15] (100,110]
#> 11 Levels: [0,10] (10,20] (20,30] (30,40] (40,50] (50,60] (60,70] ... (100,110]

Created on 2022-06-13 by the reprex package (v2.0.1)

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66