【问题标题】:How can I divide value across periods in R?如何在 R 中跨时期划分价值?
【发布时间】:2018-12-03 16:46:47
【问题描述】:

我正在处理来自一家信用卡公司的采购小组,其中包含几笔分期付款。我只有这些购买的总价值,但我想知道客户每月支付的实际价值。以下是一些示例数据:

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)

【问题讨论】:

  • 请检查您最后的值第 6 行支出 = 40 是否正确。我看不出它的逻辑是正确的
  • 上期60元购买的第二期30加上本期唯一期的10。
  • 为什么不像第一个那样 50/2 + 60/2 + 10/1
  • 因为如果您在第 1 期支付了 25 美元,在第 2 期支付了 25 美元,那么就没有分期付款需要支付了。在第 3 期支付 50/2 意味着为价值 50 的商品支付 75。

标签: r data.table zoo


【解决方案1】:

我想我明白了:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-14
    • 1970-01-01
    • 2021-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多