I have cohort study data with start and end dates for each patient. Each patient enters and exists the study at completely different dates. I would like to calculate the prevalence of a disease in each month. How can I aggregate the data in a way that shows the total number of study patients per month (n_total) and total number of patients with the disease (n_disease) per month which would allow me to calculate the prevalence (n_disease/n_total) noting that for months where there are 0 patients and 0 prevalence I still want a row to be present and to say 0 for prevalence. Also, if people leave in say for example in May, they would still be counted for the population of that month even if they were only present for some of that month.
This is how my data currently looks like:
patid | start_date | end_date | disease | disease_date |
---|---|---|---|---|
1 | 01/03/2016 | 31/08/2021 | yes | 15/11/2017 |
2 | 24/03/2020 | 31/08/2021 | no | NA |
3 | 01/03/2020 | 23/08/2021 | yes | 15/08/2020 |
4 | 24/03/2016 | 01/08/2019 | no | NA |
5 | 24/03/2018 | 17/08/2020 | no | NA |
6 | 01/03/2016 | 04/08/2018 | yes | 01/01/2017 |
7 | 01/03/2016 | 31/08/2018 | yes | 18/03/2017 |
Sample data:
df <- data.frame(patid=c("1","2","3","4","5","6","7"),
start_date=c("01/03/2016","24/08/2016",
"01/01/2016","24/02/2016",
"24/04/2016","01/04/2016",
"01/09/2016"),
end_date=c("31/12/2016","31/12/2016",
"23/12/2016","01/08/2016",
"17/06/2016","04/05/2016",
"31/10/2016"),
disease=c("yes","no","yes","no",
"no","yes","yes"),
disease_date=c("15/08/2016",NA,
"15/08/2016",NA,NA,
"01/05/2016","31/10/2016") )
The outcome of this would look like this:
structure(list(month_year = c("01/2016", "02/2016", "03/2016",
"04/2016", "05/2016", "06/2016", "07/2016", "08/2016", "09/2016",
"10/2016", "11/2016", "12/2016"), n_total = c("1", "2", "3",
"5", "5", "4", "3", "4", "4", "4", "3", "3"), n_disease = c("0",
"0", "0", "0", "1", "0", "0", "2", "0", "1", "0", "0"), prevalence = c("0",
"0", "0", "0", "0.2", "0", "0", "0.5", "0", "0.25", "0", "0")), class = "data.frame", row.names = c(NA,
-12L))