Divide the lines into 10 groups, each of which has the same amount of value

I have data with 2 columns, ID and Revenue. I want to create a column that will divide the data into 10 groups, each of which has 10% of the total income. The quantile method gives me 10 groups with an equal amount of ID, not income.

idrev[ , decile := cut(Revenue,
                    breaks = quantile(Revenue, probs = seq(0, 1, by = 1/10)),
                    labels = 1:10, right = FALSE)]

I get the following result like

    N   Revenue %Revenue
 100    $3,992  80%
 100    $518    10%
 100    $236    5%
 100    $126    3%
 100    $68 1%
 100    $35 1%
 100    $16 0%
 100    $6  0%
 100    $2  0%
 100    $1  0%
 1,000  $5,000  100%

while I'm looking for this result

    N   Revenue %Revenue
 798    500 10%
 104    500 10%
 47     500 10%
 25     500 10%
 14     500 10%
 7  500 10%
 3  500 10%
 2  500 10%
 1  500 10%
 1  500 10%
 1,000  $5,000  100%

Please suggest a solution for this in R.

Adding code to get data and sample statistics

library(Hmisc);library(data.table)
set.seed(123)
idrev<-data.table(ID=1:1000, Revenue=sample(100,1000,replace=T))
idrev[,.(.N,sum(Revenue))] #Check total revenue
idrev[ , decile := cut2(Revenue,g=10)]
idrev[,.(.N,sum(Revenue)),by=decile][order(decile)]
+4
source share
1 answer

Here is just the method data.tablethat should get you there:

idrev[order(Revenue), revDec := 10 * ceiling(10 * (cumsum(Revenue) / sum(Revenue)))]

This is a direct calculation of deciles after arranging the rows by income.

Here is the result of adding revenue to revDec:

idrev[, .(Revenue=sum(Revenue)), by="revDec"]
    revDec Revenue
 1:     10    5004
 2:     70    5070
 3:     20    5039
 4:     80    5025
 5:     90    4974
 6:     30    4974
 7:     40    5059
 8:     50    5026
 9:    100    5091
10:     60    4960

5000.

+5

Source: https://habr.com/ru/post/1652452/


All Articles