maira khan
maira khan

Reputation: 43

counting total occurrence of each session id and start and end time per SessionID

suppose i have a dataframe

> str(data)
'data.frame':   2538 obs. of  5 variables:
 $ X        : int  1 2 3 4 5 6 7 8 9 10 ...
 $ SessionID: int  13307 21076 27813 8398 23118 12256 28799 11457 7542 19261 ...
 $ Timestamp: POSIXct, format: "2014-04-06 18:42:05" "2014-04-03 15:27:48" "2014-04-04 09:10:14" "2014-04-03 23:39:20" ...
 $ ItemID   : int  214684513 214718203 214716928 214826900 214838180 214717318 214821307 214537967 214835775 214706432 ...
 $ Price    : int  0 0 0 0 0 0 0 0 0 0 ...

and i want to count total occurrance of each SessionID and each session start and end time mean i want output like this

> data
    session id     timestamp           price       
      1         2014-04-0618:42:05.822     0     
      1         2014-04-0618:42:06.800     1
      1         2014-04-0618:42:06.820     0
      2         2014-04-0315:27:48.118     0
      2         2014-04-0315:27:49.440     0

>  result   
session id   session start and end time                        num of occurrence   
 1           2014-04-0618:42:05.822, 2014-04-0618:42:06.820       3
 2           2014-04-0315:27:48.118, 2014-04-0315:27:49.440       2

Upvotes: 0

Views: 122

Answers (1)

DanY
DanY

Reputation: 6073

The data.table way:

library(data.table)
setDT(data)

data[ , .(session_start = min(Timestamp), 
          session_end   = max(Timestamp), 
          num_occurance = .N), by=Session_ID]

Upvotes: 1

Related Questions