tidybins



library(tidybins)
suppressPackageStartupMessages(library(dplyr))

Bin Value

Binning by value is the only original binning method implemented in this package. It is inspired by the case in marketing when accounts need to be binned by their sales. For example, creating 10 bins, where each bin represent 10% of all market sales. The first bin contains the highest sales accounts, thus has the small total number of accounts, whereas the last bin contains the smallest sales accounts, thus requiring the most number of accounts per bin to reach 10% of the market sales.


tibble::tibble(SALES = as.integer(rnorm(1000L, mean = 10000L, sd = 3000))) -> sales_data

sales_data %>% 
  bin_cols(SALES, bin_type = "value") -> sales_data1

sales_data1
#> # A tibble: 1,000 × 2
#>    SALES SALES_va10
#>    <int>      <int>
#>  1  6285          1
#>  2  5262          1
#>  3  6802          1
#>  4  7620          2
#>  5  8866          3
#>  6  4508          1
#>  7  8653          3
#>  8 11133          6
#>  9  9329          3
#> 10 11141          6
#> # ℹ 990 more rows

Notice that the sum is equal across bins.

sales_data1 %>% 
  bin_summary() %>% 
  print(width = Inf)
#> # A tibble: 10 × 14
#>    column method      n_bins .rank  .min  .mean  .max .count .uniques
#>    <chr>  <chr>        <int> <int> <int>  <dbl> <int>  <int>    <int>
#>  1 SALES  equal value     10    10 14911 16106. 20146     64       64
#>  2 SALES  equal value     10     9 13659 14282. 14909     71       68
#>  3 SALES  equal value     10     8 12593 13119. 13655     78       75
#>  4 SALES  equal value     10     7 11673 12077. 12583     84       81
#>  5 SALES  equal value     10     6 10908 11291. 11662     91       82
#>  6 SALES  equal value     10     5 10193 10525. 10887     97       94
#>  7 SALES  equal value     10     4  9422  9798. 10159    104       96
#>  8 SALES  equal value     10     3  8615  9007.  9420    113      106
#>  9 SALES  equal value     10     2  7408  8063.  8612    126      122
#> 10 SALES  equal value     10     1  2560  5922.  7394    172      165
#>    relative_value    .sum   .med   .sd width
#>             <dbl>   <int>  <dbl> <dbl> <int>
#>  1          100   1030783 15617  1204.  5235
#>  2           88.7 1014029 14267   399.  1250
#>  3           81.5 1023316 13102.  314.  1062
#>  4           75.0 1014475 12002.  294.   910
#>  5           70.1 1027466 11279   237.   754
#>  6           65.4 1020966 10488   193.   694
#>  7           60.8 1019012  9819   213.   737
#>  8           55.9 1017847  9001   241.   805
#>  9           50.1 1015888  8122   374.  1204
#> 10           36.8 1018518  6090. 1138.  4834