{"cells":[{"metadata":{"_uuid":"4c47e1bbfa8041792ff897f0f1461d29d732ca8e"},"cell_type":"markdown","source":"## Feature Engineering\nThe below function will create a new field called \"time_diff\" which calculates the duration between successive sessions for a given user.  It is calculated using the visitStartTime field and the default unit of time is in seconds, but that could be changed to minutes, hours, days etc.  Hope this helps!!"},{"metadata":{"_uuid":"34305e90316a61b72aa637ef07f348a6dde5624c","_execution_state":"idle","trusted":true},"cell_type":"code","source":"time_since_last_session <- function(df, time_unit='secs'){\n  time_since_df <- df %>%\n    select(fullVisitorId, sessionId, visitStartTime) %>%\n    group_by(fullVisitorId) %>%\n    arrange(visitStartTime) %>%\n    mutate(time_diff = as.numeric(visitStartTime - lag(visitStartTime), units = time_unit))\n  time_since_df[is.na(time_since_df$time_diff), \"time_diff\"] <- 0\n  df <- merge(df, time_since_df[, c('sessionId','time_diff')], by='sessionId', all.x=TRUE)\n}","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"R","language":"R","name":"ir"},"language_info":{"mimetype":"text/x-r-source","name":"R","pygments_lexer":"r","version":"3.4.2","file_extension":".r","codemirror_mode":"r"}},"nbformat":4,"nbformat_minor":1}