首页 > 解决方案 > 如何在 r 中建立累积相乘元素的运行计数?

问题描述

我正在处理一个大型数据框,我需要/想要使用更高效的代码。

这是我的出发点:

library(data.table)
dt<-data.table(Customer = c("John","Sally","Michael","David"), 
Premium=c(1000,950,1125,1500),
Factor_1=1.2, 
Factor_2 =c(.98,.95,.9,.75),Factor_3=c(1,1.2,1.4,1.5))

这是想要的结果(我想创建 Premium_1、Premium_2、Premium_3):

Inefficient_code_answer<-dt%>%
  mutate(Premium_1 = Premium*Factor_1)%>%
  mutate(Premium_2 = Premium*Factor_1*Factor_2)%>%
  mutate(Premium_3 = Premium*Factor_1*Factor_2*Factor_3)

我尝试使用 purrr

dt%>%
mutate(Premium_3 = Premium * pmap_dbl(list(Factor_1:Factor_3),prod))

但是 list() 不能很好地与“ : ”序列配合使用(除非我只是不知道如何)。

我需要将大约 25 到 30 个因素应用于基本保费,并且我需要每一步的保费值。我目前将所有内容都输入到脚本中,但是当我想添加或删除一个步骤(或因素)时,这是一场噩梦。

谢谢

标签: rdplyrdata.tablepurrr

解决方案


dplyr当您处理列而不是跨行时,R(尤其是 )中的计算通常更容易。因此,您可以先将数据转换为长格式,然后使用cumprod()

dt_long <- dt %>%
    pivot_longer(
        cols = Factor_1:Factor_3,
        names_to = "Factor",
        names_prefix = "Factor_",
        values_to = "Value"
    )

dt_long <- dt_long %>%
    group_by(Customer) %>%
    mutate(Result = Premium * cumprod(Value))

输出:

# A tibble: 12 x 5
# Groups:   Customer [4]
   Customer Premium Factor Value Result
   <chr>      <dbl> <chr>  <dbl>  <dbl>
 1 John        1000 1       1.2   1200 
 2 John        1000 2       0.98  1176 
 3 John        1000 3       1     1176 
 4 Sally        950 1       1.2   1140 
 5 Sally        950 2       0.95  1083 
 6 Sally        950 3       1.2   1300.
 7 Michael     1125 1       1.2   1350 
 8 Michael     1125 2       0.9   1215 
 9 Michael     1125 3       1.4   1701.
10 David       1500 1       1.2   1800 
11 David       1500 2       0.75  1350.
12 David       1500 3       1.5   2025.

推荐阅读