按客户年数划分成本

时间:2019-03-13 20:10:32

标签: r date

我有一个数据集

dt <- data.table(Customer = c("a", "a", "c"), months = c(12, 24, 37), Date = c("2019-02-23","2019-03-31","2019-10-01"), Cost = c("100","200","370"))

我希望按年细分成本,并按行号回头客

dt$years<- ceiling(dt$months/12)
new.months <- ifelse(dt$months%%dt$years==0,dt$years,dt$years+1)

dt %>% mutate(Date = as.Date(Date), rn = row_number()) %>% 
  slice(rep(row_number(), ceiling(new.months))) %>%
  group_by(Customer, rn) %>%
  mutate(Date = seq(first(Date), by="1 year", length.out=n()))

我得到以下输出

 Customer months Date       Cost  years    rn
  <chr>     <dbl> <date>     <chr> <dbl> <int>
1 a            12 2019-02-23 100    1        1
2 a            24 2019-03-31 200    2        2
3 a            24 2020-03-31 200    2        2
4 c            37 2019-10-01 370    3.08     3
5 c            37 2020-10-01 370    3.08     3
6 c            37 2021-10-01 370    3.08     3
7 c            37 2022-10-01 370    3.08     3

但是,所需的输出将在“费用”列中显示如下:

  <chr>     <dbl> <date>     <chr> <dbl> <int>
1 a            12 2019-02-23 100    1        1
2 a            24 2019-03-31 100    2        2
3 a            24 2020-03-31 100    2        2
4 c            37 2019-10-01 120    3.08     3
5 c            37 2020-10-01 120    3.08     3
6 c            37 2021-10-01 120    3.08     3
7 c            37 2022-10-01  10    3.08     3

我将不胜感激。

谢谢。

1 个答案:

答案 0 :(得分:0)

months_to_year函数将整数n分解为12s的bin。例如,months_to_year(37)给出'12 12 12 1'

months_to_year <- function(n){
  if(n%%12==0) y <- rep(12, n %/%  12) else y <- c(rep(12, n %/%  12), n %% 12)
  return(y)
}

以您的代码为基础,

dt$years<- dt$months/12
dt$Cost <- as.numeric(dt$Cost)
dt %>% mutate(Date = as.Date(Date), rn = row_number()) %>% 
  slice(rep(rn, ceiling(months/12)))%>%
  group_by(Customer, rn) %>%
  mutate(months1 = months_to_year(first(months)),
         Date = seq(first(Date), by="1 year", length.out=n()),
         Cost = Cost/months * months1)

## A tibble: 7 x 7
## Groups:   Customer, rn [3]
#  Customer months Date        Cost years    rn months1
#  <chr>     <dbl> <date>     <dbl> <dbl> <int>   <dbl>
#1 a            12 2019-02-23   100  1        1      12
#2 a            24 2019-03-31   100  2        2      12
#3 a            24 2020-03-31   100  2        2      12
#4 c            37 2019-10-01   120  3.08     3      12
#5 c            37 2020-10-01   120  3.08     3      12
#6 c            37 2021-10-01   120  3.08     3      12
#7 c            37 2022-10-01    10  3.08     3       1