Here, how I would like to do this using data.table::foverlaps
First convert TimeStamp to the correct POSIXct
library(data.table) setDT(df)[, TimeStamp := as.POSIXct(TimeStamp, format = "%Y-%m-%d %I:%M:%S %p")]
Then we will create a temporary dataset where Category == 1 will be merged. We will also create an "end" column and a key "start" and "end" columns.
df2 <- setkey(df[Category == 1L][, TimeStamp2 := TimeStamp], TimeStamp, TimeStamp2)
Then we will do the same for df , but set the intervals to 10 minutes
setkey(df[, `:=`(start = TimeStamp - 600, end = TimeStamp + 600)], start, end)
Then it remains only to run foverlaps and a subset using consistent incidents
indx <- foverlaps(df, df2, which = TRUE, nomatch = 0L)$xid df[indx, .(TimeStamp, Category)]
David Arenburg
source share