如何匹配 R 中的时间,忽略秒数? (match/trunc 的意外行为)

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

我有一个时间戳列表 -- 每分钟加几秒一个。现在我想使用 R 在该列表中查找参考时间,只考虑日期+小时+分钟而忽略秒。

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")

我尝试使用 trunc(..., "mins")match() 的组合来查找所需时间的索引。但是,这会产生一些意想不到的结果:

以下内容应在“2016-10-09T23:15:03”处找到条目索引,但结果却是 idx==NA_integer.

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

奇怪的是,以下(将输入削减为 10 个时间戳)在 idx==9 处找到了搜索时间。

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

显然,我犯了一些错误或者对 trunc(..., "mins")match() 所做的事情有一些错误的假设。

版本信息
R 版本 3.3.1 (2016-06-21)
平台:x86_64-w64-mingw32/x64(64 位)
运行 Win10

发生错误的原因是因为您的时间存储为 POSIXlt 个对象,并且(出于某种原因)match 不工作。

您可以:

  1. 转换为 POSIXct 个对象
  2. 使用pmatchwhich

使用POSIXct

区别在于POSIXlt是一个列表POSIXct是一个数字.

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

使用pmatchwhich

您可以使用 pmatch 代替 match,或者您可以使用 which 进行等式测试。

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

which:

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