Using the data.table-package, you can approach it as follows:
library(data.table)
setDT(df)[, .(yr = first_occupancy:(first_occupancy + no_dwellings %/% 60),
dw = c(rep(60, no_dwellings %/% 60), no_dwellings %% 60))
, by = .(project, no_dwellings, first_occupancy)
][, dcast(.SD, project + no_dwellings + first_occupancy ~ paste0('year_',yr), value.var = 'dw', fill = 0)]
which gives:
project no_dwellings first_occupancy year_2019 year_2020 year_2021 year_2022
1: A 150 2020 0 60 60 30
2: B 180 2019 60 60 60 0
The same logic applied to tidyverse:
library(dplyr)
library(tidyr)
df %>%
group_by(project) %>%
do(data.frame(no_dwellings = .$no_dwellings, first_occupancy = .$first_occupancy,
yr = paste0('year_',.$first_occupancy:(.$first_occupancy + .$no_dwellings %/% 60)),
dw = c(rep(60, .$no_dwellings %/% 60), .$no_dwellings %% 60))) %>%
spread(yr, dw, fill = 0)
source
share