data.table 中的 IBNR 发展因子计算

问题描述 投票:0回答:1

给出下表:

IBNR <- data.table(IncurredYear=c(2020,2020,2020,2020,2021,2021,2021,2022,2022,2023),
                   DevYear=c(0,1,2,3,0,1,2,0,1,0),
                  Amount=c(100,80,70,50,70,40,35,50,45,80))

我想计算得到“累计金额”:

IBNRCumulative <- data.table(IncurredYear=c(2020,2020,2020,2020,2021,2021,2021,2022,2022,2023),
                   DevYear=c(0,1,2,3,0,1,2,0,1,0),
                   Amount=c(100,80,70,50,70,40,35,50,45,80),
                   AmountCumulative=c(100,180,250,300,70,110,145,50,95,80))

从长到宽重塑后:

IBNRtriang <- dcast(IBNRCumulative, IncurredYear ~ DevYear, fun.aggregate = list(sum), value.var = c("AmountCumulative"))

我想导出 DevFactors:

DevelopmentFactor <- data.table(DevYear=c(0,1,2,3),
                                DevFactor = c(1.75, 1.362, 1.2, 1))

其中:1.75 = (180+110+95)/(100+70+50)、1.362 = (250+145)/(180+110) 依此类推,最后一位应为 1。 你能帮我找到一种紧凑而优雅的方式来完成它吗?谢谢。

r data-wrangling
1个回答
0
投票

第一部分可以这样完成:

setorder(IBNR, IncurredYear, DevYear)
IBNRCumulative  <- IBNR[, AmountCumulative := cumsum(Amount), by = c('IncurredYear')]
© www.soinside.com 2019 - 2024. All rights reserved.