【问题标题】:R dplyr - running total with row-wise calculationsR dplyr - 逐行计算的总计
【发布时间】:2020-03-18 22:29:28
【问题描述】:

我有一个跟踪与银行帐户相关的活动的数据框(示例如下)。

初始余额为 5,000 美元(type“初始”)。如果 type 为“in”,则表示现金存款。在本例中,每笔存款为 1,000 美元。如果type 为“out”,表示从账户中提款。在本例中,每次提款为账户余额的 10%。

data <- tibble(
  activity=1:6,
  type=c("initial","in","out","out","in","in"),
  input=c(5000,1000,10,10,1000,1000))

是否有 dplyr 解决方案来跟踪每个活动之后的余额?我尝试了几种方法,但似乎找不到有效计算运行总计和提款金额(取决于运行总计)的方法。

对于这个例子,输出应该是:

result <- tibble(
  activity=1:6,
  type=c("initial","in","out","out","in","in"),
  input=c(5000,1000,10,10,1000,1000),
  balance=c(5000,6000,5400,4860,5860,6860))

提前感谢您的任何建议或建议!

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    您可以使用purrr::accumulate2() 来根据type 的值进行计算:

    library(dplyr)
    library(purrr)
    library(tidyr)
    
    data %>%
      mutate(balance = accumulate2(input, type[-1], .f = function(x, y, type) if(type == "out") x - x * y/100 else x + y)) %>%
      unnest(balance) 
    
    # A tibble: 6 x 4
      activity type    input balance
         <int> <chr>   <dbl>   <dbl>
    1        1 initial  5000    5000
    2        2 in       1000    6000
    3        3 out        10    5400
    4        4 out        10    4860
    5        5 in       1000    5860
    6        6 in       1000    6860
    

    【讨论】:

    • 我正在使用类似的选项data %&gt;% mutate(balance = purrr::accumulate2(input, type[-1], ~ if(..3 == 'in') ..2 + ..1 else ..1 - ..1 * ..2/100)) %&gt;% unnest(c(balance))
    • 感谢您在如此短的时间内提供有效的解决方案。与我的 while-loop 方法相比,它绝对更优雅。
    猜你喜欢
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    • 2021-02-22
    • 1970-01-01
    • 2020-02-02
    • 2015-06-17
    • 1970-01-01
    相关资源
    最近更新 更多