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

Thi*_*dge 1 time r 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)
Run Code Online (Sandbox Code Playgroud)

我想计算每年为每个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)
Run Code Online (Sandbox Code Playgroud)

h3r*_*m4n 5

这可以通过dplyr包装轻松完成:

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

输出是:

     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
Run Code Online (Sandbox Code Playgroud)

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

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

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

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