计算一个时间序列中每个单位的累积百分比

时间:2016-10-16 18:53:24

标签: r time cumulative-sum

我有以下数据:

ID <- c(1, 2, 1, 2, 1, 2)
year  <- c(1, 1, 2, 2, 3, 3)
population.served  <- c(100, 200, 300, 400, 400, 500)
population  <- c(1000, 1200, 1000, 1200, 1000, 1200)
all <- data.frame(ID, year, population.served, population)

我想计算按年份为每个ID服务的人口百分比。我试过这个,但我只计算每年服务的百分比。我需要一些方法来迭代每个ID和年份,以捕获累积和作为分子。

我希望数据看起来像这样:

ID <- c(1, 2, 1, 2, 1, 2)
year  <- c(1, 1, 2, 2, 3, 3)
population.served  <- c(100, 200, 300, 400, 400, 500)
population  <- c(1000, 1200, 1000, 1200, 1000, 1200)
cumulative.served <- c(10, 16.7, 40, 50, 80, 91.7)
all <- data.frame(ID, year, population.served, population, cumulative.served)

1 个答案:

答案 0 :(得分:5)

使用dplyr包可以轻松完成此操作:

all %>% 
  arrange(year) %>% 
  group_by(ID) %>% 
  mutate(cumulative.served = round(cumsum(population.served)/population*100,1))

然后输出:

     ID  year population.served population cumulative.served
  <dbl> <dbl>             <dbl>      <dbl>             <dbl>
1     1     1               100       1000              10.0
2     2     1               200       1200              16.7
3     1     2               300       1000              40.0
4     2     2               400       1200              50.0
5     1     3               400       1000              80.0
6     2     3               500       1200              91.7

或者使用快速data.table包的方式类似:

library(data.table)
setDT(all)[order(year), cumulative.served := round(cumsum(population.served)/population*100,1), by = ID]

经过一些反复试验,我还想出了一个基本的R方法:

all <- all[order(all$ID, all$year),]
all$cumulative.served <- round(100*with(all, ave(population.served, ID, FUN = cumsum))/all$population, 1)