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

Calculate cumulative percentage for each unit over a time series

我有以下数据:

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)

这可以通过 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)