[英]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
軟件包輕松完成此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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.