【问题标题】:Split amount pro rata monthly每月按比例分割金额
【发布时间】:2021-11-25 22:19:48
【问题描述】:

大家好,女士们,先生们, 在这里你可以看到我的输入文件:

Input <- data.table(
  id = c("x1","x2","x3"),
  from = c("2020-01-01","2020-02-15","2019-01-15"), 
  to = c("2020-12-31","2021-02-14","2021-02-14"), 
  Amount = c(120, 120, 240) 
)

基本上我想按月分配金额。你能推荐一种快速而优雅的方法吗?

这是我想为其中一个 id 获取的内容(对于另一个 id,逻辑应该相同)。

Output_x2 <- data.table(
  id = c("x2"),
  Period = c(2021), 
  to = c(202002, 202003, 202004, 202005, 202006, 202007, 202008, 202009, 202010, 202011, 202012, 202101, 202102), 
  Amount_ProRata = c(5, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,5) 
)

【问题讨论】:

    标签: r date time datatable reshape


    【解决方案1】:

    一个可能的解决方案:

    library(data.table)
    library(tidyverse)
    library(lubridate)
    
    spread <- function(x,y,z,value)
    {
      nMonths <- as.duration(y %--% z) %>% 
        as.numeric("months") %>% 
        round(0)
      
      frac1 <- y %>% 
        {day(.)/days_in_month(.)} %>% 
        round(1)
      
      frac2 <- z %>% 
        {day(.)/days_in_month(.)} %>% 
        round(1)
      
      wholem <- round(nMonths - frac1 - frac2,0)
     
      splita <- (value/nMonths) * c(frac1,rep(1,wholem),frac2)
      splita <- splita[splita > 0]
        
      months <- seq(ymd(y),ymd(z)+2, by = "months")
      months <- months[1:length(splita)]
      
      df <- data.frame(id=x,
                       Period=year(months),
                       to=paste0(year(months),sprintf("%02d",month(months))),
                       Amount_ProRata=splita)
    }
    
    map_dfr(1:nrow(Input),
             ~ spread(Input$id[.x], Input$from[.x], Input$to[.x], Input$Amount[.x]))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-19
      • 2020-01-08
      • 1970-01-01
      • 2021-06-17
      • 1970-01-01
      • 2020-02-21
      • 1970-01-01
      • 2016-01-13
      相关资源
      最近更新 更多