I would like to construct a "cumulative sum", counting the number of observations in a group that have ended before the observation in question started.
I prefer answers using dplyr, but prioritize low memory overhead as this is a huge dataset.
MWE below, where the variable I'd like to create is called "prior_ended_obs".
mwe <- data.frame(group = c("a", "a", "a", "a", "a", "a", "a", "a", "a", "b", "b", "b"),
start = c("1/1/1990", "1/2/1990", "1/3/1990", "1/3/1990", "1/3/1990", "1/4/1990", "1/5/1990", "1/6/1990", "1/7/1990", "1/1/1990", "1/2/1990", "1/3/1990"),
end = c("1/2/1990", "1/2/1990", "1/3/1990", "1/4/1990", "1/5/1990", "1/5/1990", "1/5/1990", "1/6/1990", "1/8/1990", "1/1/1990", "1/2/1990", "1/3/1990"),
prior_ended_obs = c(0, 0, 2, 2, 2, 3, 4, 7, 8, 0, 1, 2)) %>%
mutate(start = mdy(start),
end = mdy(end)) %>%
group_by(group) %>%
mutate(lag_end = lag(end),
ones = 1,
cumsum = cumsum(ones)-1)