My data are as follows:
data <- structure(list(year = c(2019L, 2019L, 2019L, 2019L, 2019L, 2020L,
2020L, 2020L, 2020L, 2020L), group = c("A", "A", "A", "B", "B",
"A", "A", "B", "B", "B"), date = c("2019-07-15", "2019-07-25",
"2019-08-01", "2019-07-15", "2019-07-30", "2020-08-01", "2020-08-03",
"2020-08-01", "2020-08-20", "2020-08-25")),
class = "data.frame", row.names = c(NA,
-10L))
I would like to calculate the number of days passed since the previous date per year per group. When I attempt to do this, the output is not grouping the data. For example, the output will calculate the number of days between group B, 2019-07-15, and group A, 2019-08-21 as a negative value, rather than calculating days passed since each date WITHIN group.
I have tried the following code, which results in the issue I describe above:
library(dplyr)
data %>%
arrange(year, group, date) %>% # To ensure dates are in chronological order within each group
mutate(date = as.Date(date)) %>%
group_by(year, group)%>%
mutate(Difference = difftime(date, lag(date), units = "days"))
Thank you in advance!