I need help calculating the time difference between sessions for users with multiple sessions. A sample of my dataset:
df <- structure(list(
sess_id = c(189, 189, 189, 167, 167, 118, 118, 118, 124, 124, 124, 124),
user_id = c("504", "504", "504", "504", "504", "505", "505", "505", "505", "505", "505", "505"),
path_id = c(1, 2, 3, 1, 2, 1, 2, 3, 1,2,3,4),
ts = c("2002-06-09 12:45:40","2002-06-09 12:46:01","2002-06-09 12:46:30","2002-06-09 12:47:00","2002-06-09 12:47:50", "2002-06-09 12:49:51", "2002-06-09 12:49:59", "2002-06-09 13:00:00", "2002-06-09 13:30:00", "2002-06-09 13:31:02", "2002-06-09 13:31:45", "2002-06-09 13:32:28")),
.Names = c("sess_id", "user_id", "path_id", "ts"),
row.names = c(NA, -12L),
class = "data.frame")
I want a column 'ts_diff' that denotes the time difference between sessions. For instance, for user_id 504: the time difference between sessions 189 and 167 is 30 seconds (2002-06-09 12:47:00 - 2002-06-09 12:46:30). And, for user_id 505: the time difference between sessions 118 and 124 is 1800 seconds (2002-06-09 13:30:00 - 2002-06-09 13:00:00).
Please note that in the real dataset a user can have one to more than four sessions. This is only a sample dataset with two sessions per user.