Reshaping data in R with "login" "logout" times
Using rowid()
from the data.table-package along with dcast
:
require(data.table)
dcast(dt, user + rowid(user, state) ~ state, value.var="datetime")
# user user_1 joined left
# 1: User1 1 2016-02-19 19:13:26 2016-02-19 19:13:32
# 2: User1 2 2016-02-19 19:21:33 2016-02-19 19:25:26
# 3: User1 3 2016-02-19 19:35:38 2016-02-19 19:42:16
# 4: User1 4 2016-02-19 19:44:15 2016-02-19 19:47:59
# 5: User1 5 2016-02-19 19:48:55 2016-02-19 19:51:06
# 6: User1 6 2016-02-19 19:52:40 <NA>
# 7: User2 1 2016-02-19 19:21:18 2016-02-19 19:30:30
# 8: User3 1 2016-02-19 19:53:15 2016-02-19 20:02:26
# 9: User3 2 2016-02-19 20:02:34 <NA>
# 10: User3 3 2016-02-19 20:13:48 <NA>
We can make use of the order of "left" and "joined", and match when one follows the other for each user.
For this I'm going to use library(data.table)
library(data.table)
setDT(df)
## order the data by user and datetime
df <- df[order(user, datetime)]
## add an 'order' column, which is a sequence from 1 to lenght()
## for each user
df[, order := seq(1:.N), by=user]
## split the left and joins
dt_left <- df[state == "left"]
dt_joined <- df[state == "joined"]
## assuming 'left' is after 'joined', shift the 'order' back for left
dt_left[, order := order - 1]
## join user an dorder (and subsetting relevant columns)
## keeping when there's a 'joined' but not a 'left'
dt <- dt_left[, .(user, order, datetime)][dt_joined[, .(user, order, datetime)], on=c("user", "order"), nomatch=NA]
## rename columns
setnames(dt, c("datetime", "i.datetime"), c("left", "joined"))
user order left joined
1: User1 1 2016-02-19 19:13:32 2016-02-19 19:13:26
2: User1 3 2016-02-19 19:25:26 2016-02-19 19:21:33
3: User1 5 2016-02-19 19:42:16 2016-02-19 19:35:38
4: User1 7 2016-02-19 19:47:59 2016-02-19 19:44:15
5: User1 9 2016-02-19 19:51:06 2016-02-19 19:48:55
6: User1 11 2016-02-19 20:48:22 2016-02-19 19:52:40
7: User1 13 2016-02-19 21:11:13 2016-02-19 21:06:20
8: User1 15 2016-02-19 21:17:33 2016-02-19 21:11:15
9: User2 1 2016-02-19 19:30:30 2016-02-19 19:21:18
10: User3 1 2016-02-19 20:02:26 2016-02-19 19:53:15
11: User3 3 2016-02-19 20:13:38 2016-02-19 20:02:34
12: User3 5 2016-02-19 20:42:27 2016-02-19 20:13:48
13: User3 7 NA 2016-02-19 20:49:31
14: User3 8 NA 2016-02-19 22:30:30
15: User4 1 2016-02-19 21:10:43 2016-02-19 20:59:58
16: User4 3 2016-02-19 22:02:45 2016-02-19 21:11:22
17: User4 5 2016-02-19 22:05:37 2016-02-19 22:05:18
18: User4 7 NA 2016-02-19 22:05:47