George Blackburn George Blackburn - 2 months ago 13
R Question

How to match time in R, ignoring seconds? (unexpected behavior of match/trunc)

I have a list of timestamps -- one every minute plus a few seconds. Now I want to use R to find a reference time in that list, considering only at date+hours+minutes while ignoring the seconds.

library(lubridate)
data <- c(
"2016-10-09T23:05:01",
"2016-10-09T23:06:01",
"2016-10-09T23:07:01",
"2016-10-09T23:08:01",
"2016-10-09T23:10:10",
"2016-10-09T23:11:01",
"2016-10-09T23:12:01",
"2016-10-09T23:13:04",
"2016-10-09T23:14:02",
"2016-10-09T23:15:03",
"2016-10-09T23:16:10"
)
dataParsed <- ymd_hms(data[])
refTime <- ymd_hms("2016-10-09T23:15:00")


I tried to use a combination of
trunc(..., "mins")
and
match()
to find the index of the wanted time. However, that produces some unexpected results:

The following should find the index for entry at "2016-10-09T23:15:03", but instead results in
idx==NA_integer
.

idx <- match(trunc(refTime,"mins"), trunc(dataParsed,"mins"))


Strangely enough, the following (with cutting the input to 10 timestamps) finds the searched time at
idx==9
.

idx <- match(trunc(refTime,"mins"), trunc(tail(dataParsed,10),"mins"))


Apparently, I made some mistake or have some wrong assumptions about what
trunc(..., "mins")
and
match()
do.

Version info

R version 3.3.1 (2016-06-21)

Platform: x86_64-w64-mingw32/x64 (64-bit)

Running on Win10

Answer

The reason the error occurs is because your times are stored as POSIXlt objects, and (for some reason) match isn't working.

You can:

  1. Convert to POSIXct objects
  2. Use pmatch or which.

Using POSIXct

The difference is that POSIXlt is a list and POSIXct is a number.

idx <- match(as.POSIXct(trunc(refTime,"mins")), as.POSIXct(trunc(dataParsed,"mins")))
#> [1] 10

Using pmatch or which

You can either use pmatch instead of match, or you can use which with an equality test.

pmatch(trunc(refTime,"mins"), trunc(dataParsed,"mins"))
#> [1] 10

Or which:

which(trunc(dataParsed,"mins") == trunc(refTime,"mins"))
#> [1] 10