У меня есть набор данных
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
Буду признателен за любую помощь.
Спасибо.