查找累积总和达到限制的最高值

Find highest values whose cumulative sum reaches limit

我有以下类型的数据框,代表每家公司每年发行的金融产品的数量,以及这些数量占每年发行总量的百分比。

  year           company       Volume     Volume Year          %
1 2013            AWK      347902000    21927606761     0.015865936
2 2013            DAR      177977000    21927606761     0.008116572
3 2013            DTC      615627000    21927606761     0.028075431
4 2013            GMT      538456000    21927606761     0.024556077
5 2013            CLW      407497000    21927606761     0.018583743
6 2013            AYI       31970000    21927606761     0.001457979

每年,我想 select 最大的发行公司,它们合计占市场总量的 70%。

我可以手动执行此操作,但我正在寻找一个可以轻松应用于我的大型数据集的公式,并且我将来可以大量使用它!

您可以先按年份和数量排序,然后使用 ave 每年 cumsum,然后 select 那些低于 70% 的数据,例如:

tt  <- read.table(header=T, text="year           company       Volume     VolumeYear          p
2013            AWK      347902000    21927606761     0.015865936
2013            DAR      177977000    21927606761     0.008116572
2013            DTC      615627000    21927606761     0.028075431
2013            GMT      538456000    21927606761     0.024556077
2013            CLW      407497000    21927606761     0.018583743
2013            AYI       31970000    21927606761     0.001457979")

tt <- tt[with(tt, order(year, -Volume)),]
tt$pc  <- with(tt, ave(p, year, FUN=cumsum))
tt[tt$pc <= .7, c("year","company")]

使用 dplyr 库(假设您的 data.frame 是 DF):

library(dplyr)

trimmed_DF = DF %>% 
   mutate(percentage = Volume/VolumeYear) %>%    # you already have this column, though.
   group_by(year) %>% 
   mutate(new_col = cumsum(percentage)) %>%
   filter(new_col > 0.30)                        # 0.3 = 1 - 0.7