George Blackburn George Blackburn - 1 year ago 61
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.

data <- c(
dataParsed <- ymd_hms(data[])
refTime <- ymd_hms("2016-10-09T23:15:00")

I tried to use a combination of
trunc(..., "mins")
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 <- match(trunc(refTime,"mins"), trunc(dataParsed,"mins"))

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

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

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

Version info

R version 3.3.1 (2016-06-21)

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

Running on Win10

Answer Source

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