如何在R的各个期间内划分价值?

时间:2018-12-03 16:46:48

标签: r data.table zoo

我正在与一个信用卡公司的采购小组合作,该小组分期进行了几次采购。我只拥有这些购买的总价值,但我想获得客户每月支付的实际价值。以下是一些示例数据:

library(data.table)

aa <- data.table('period' = c(1, 2, 3), 'customer' = 1, 'purchase' = c(90, 20, 10),
                     'installments' = c(3, 2, 1))
bb <- data.table('period' = c(1, 2, 3), 'customer' = 2, 'purchase' = c(50, 60, 10),
                     'installments' = c(2, 2, 1))
cc <- rbind(aa, bb)
   period customer purchase installments
1:      1        1      100            3
2:      2        1       20            2
3:      3        1       10            1
4:      1        2       50            2
5:      2        2       60            2
6:      3        2       10            1

我想要的结果是:

   period customer purchase installments spending
1:      1        1       90            3       30  (90/3)
2:      2        1       20            2       40  (90/3 + 20/2)            
3:      3        1       10            1       50  (90/3 + 20/2 + 10)
4:      1        2       50            2       25  (50/2)
5:      2        2       60            2       55  (50/2 + 60/2)
6:      3        2       10            1       40  (60/2 + 10)

1 个答案:

答案 0 :(得分:0)

我想我明白了

dt <- cc[rep(1:.N, installments)][, Indx := 1:.N, by = .(period, customer, installments)]
dt[, period := period + Indx - 1]
dt[, inst_pay := purchase/installments]
dt[, spending := sum(inst_pay), by = .(period, customer)]
setorder(dt, customer, period)
print(dt)

    period customer purchase installments Indx inst_pay spending
 1:      1        1       90            3    1       30       30
 2:      2        1       90            3    2       30       40
 3:      2        1       20            2    1       10       40
 4:      3        1       90            3    3       30       50
 5:      3        1       20            2    2       10       50
 6:      3        1       10            1    1       10       50
 7:      1        2       50            2    1       25       25
 8:      2        2       50            2    2       25       55
 9:      2        2       60            2    1       30       55
10:      3        2       60            2    2       30       40
11:      3        2       10            1    1       10       40