Suppose I have
dt <- as.POSIXct(c("2020-01-01 09:30:00",
"2020-01-01 09:31:00",
"2020-01-01 09:35:00",
"2020-01-01 09:36:00",
"2020-01-01 09:37:00",
"2020-01-01 09:40:00",
"2020-01-01 09:50:00",
"2020-01-01 09:51:00",
"2020-01-01 09:52:00"))
and I want to find the first minute for every time say 3 consecutive minutes are in dt, i.e.
"2020-01-01 09:35:00" "2020-01-01 09:50:00".
How would I be able to do this?
CodePudding user response:
Here is a base R approach -
with(rle(as.integer(c(difftime(dt[-1],dt[-length(dt)],units = 'mins'),0)) == 1),
dt[!duplicated(rep(seq_along(values), lengths)) &
rep(lengths >= 2 & values, lengths)])
#[1] "2020-01-01 09:35:00 08" "2020-01-01 09:50:00 08"
difftimecalculates difference between consecutive timestamps.- Using
rlewe calculate lengths whose difference between timestamp is 1 minute. - Return only the starting timestamp of groups where length is greater than 2.
