Currently I am writing my master's thesis, however, I have some issues with combining rows on multiple conditions. I have illustrated my problem and desired outcome below. I hope you can help me :).
This is an example of how my dataset looks like:
df <- data.frame(
userID = c(1, 1, 1, 1, 1, 2, 2, 3, 3, 3, 3),
sessionID = c(1, 2, 3, 4, 5, 1, 2, 1, 2, 3, 4),
date = as.Date(c("2019-03-15", "2019-03-18", "2019-03-19", "2019-03-21","2019-03-30", "2019-04-05",
"2019-06-06", "2019-11-22", "2019-12-22", "2019-12-24", "2020-01-15"),
format = "%Y-%m-%d"),
purchase=c(0,1,0,0,0,0,0,0,0,1,0))
Now, I have calculated the difference via diff via dplyr:
library(dplyr)
df <- df %>%
group_by(userID) %>%
mutate(diff = date - lag(date))
However, I want to combine the rows if there is < 10 days of difference between them. I would like that the 10 days window resets every time there is an activity (a new sessionID). Furthermore, when purchase is 1 then it stops, and the 10 day window will start again when there is a new sessionID.
I have tried many things with the functions filter and summarise in dplyr, but it gives not the desired result. Besides, I do not really know how to include the purchase condition.
My desired outcome would look like this:
df2 <- data.frame(
userID = c(1, 1, 2, 2, 3, 3, 3),
sessionID = c("1 + 2", "3 + 4 + 5", "1", "2", "1", "2 + 3", "4"),
date.start = as.Date(c("2019-03-15","2019-03-19", "2019-04-05",
"2019-06-06", "2019-11-22", "2019-12-22", "2020-01-15"),
format = "%Y-%m-%d"),
date.end = as.Date(c("2019-03-18", "2019-03-30", "2019-04-05", "2019-06-06",
"2019-11-22", "2019-12-24", "2020-01-15"), format = "%Y-%m-%d"),
purchase=c(1,0,0,0,0,1,0))
I hope you can help me :) Thanks in advance!