disclosure - this is my first SO question, my apologies if this is a repeat question but I have looked for a while now and have not found an answer to this particular scenario
R version: 3.4.2
I want an efficient way of grouping data by a certain identifier and then summarize based on a condition - dynamically for each row. Specifically, group by ID and then sum how many instances another variable occurred (urgent visits) IF the other instance was within 1 year of the current row.
Here is an example of what the data looks like to start:
Updated to include example of 2 urgent cases
library(lubridate)
> dat <- data.frame("ID" = c(6,6,6,7,7,10,11,11,11),
"Admit_Dt" = as.Date(c('2013-08-12', '2013-12-12', '2016-01-03','2011-04-01', '2011-09-20','2012-02-19','2014-06-24','2014-08-12','2014-09-01')),
"Urgent" = c(0,1,1,1,0,0,1,1,1))
> dat
| ID | Admit_Dt | Urgent|
| 6 | 2013-08-12 | 1|
| 6 | 2013-12-12 | 0|
| 6 | 2016-01-03 | 1|
| 7 | 2011-04-01 | 1|
| 7 | 2011-09-20 | 0|
| 10 | 2012-02-19 | 0|
| 11 | 2014-06-24 | 1|
| 11 | 2014-08-12 | 1|
| 11 | 2014-09-01 | 1|
I want to first group by ID and then sum how many urgent visits occurred within one year of each Admit_Dt for a given group.
This over complicated code below produces what I want but the dataset I am working with is very large and I this is pretty inefficient. I'm curious if there is a method using 'dplyr' to achieve what I am trying to do:
> dat$Urgent_1yrSum <- unlist(sapply(1:length(unique(dat$ID)), function(i) {
grouped <- subset(dat, ID == unique(dat$ID)[i])
output <- do.call(rbind, lapply(1:nrow(grouped), function(y){
urgent_sum_1year <- sum(grouped[grouped$Admit_Dt < grouped$Admit_Dt[y] & grouped$Admit_Dt > (grouped$Admit_Dt[y] - dyears(1)), "Urgent"])
}))
return(output)
}
))
> dat
| ID | Admit_Dt | Urgent| Urgent_1yrSum|
| 6 | 2013-08-12 | 1| 0|
| 6 | 2013-12-12 | 0| 1|
| 6 | 2016-01-03 | 1| 0|
| 7 | 2011-04-01 | 1| 0|
| 7 | 2011-09-20 | 0| 1|
| 10 | 2012-02-19 | 0| 0|
| 11 | 2014-06-24 | 1| 0|
| 11 | 2014-08-12 | 1| 1|
| 11 | 2014-09-01 | 1| 2|
Thanks for any help!!