在 R 中查找前一个小时和下一个小时

Find previous hour and next hour in R

假设我通过 "2015-01-01 01:50:50",那么它应该 return "2015-01-01 01:00:00""2015-01-01 02:00:00"。如何在 R 中计算这些值?

假设您的时间是一个变量 "X",您可以使用 roundtrunc

尝试:

round(X, "hour")
trunc(X, "hour")

这仍然需要一些工作来确定这些值实际上是向上舍入还是向下舍入(对于 round)。所以,如果你不想考虑这个,你可以考虑使用 "lubridate" 包:

X <- structure(c(1430050590.96162, 1430052390.96162), class = c("POSIXct", "POSIXt"))
X
# [1] "2015-04-26 17:46:30 IST" "2015-04-26 18:16:30 IST"

library(lubridate)
ceiling_date(X, "hour")
# [1] "2015-04-26 18:00:00 IST" "2015-04-26 19:00:00 IST"
floor_date(X, "hour")
# [1] "2015-04-26 17:00:00 IST" "2015-04-26 18:00:00 IST"

我会使用以下使用基数 R 的包装器(您可以使用 strptime 函数中的 tz 参数指定您的时区)

Myfunc <- function(x){x <- strptime(x, format = "%F %H") ; c(x, x + 3600L)} 
Myfunc("2015-01-01 01:50:50")
## [1] "2015-01-01 01:00:00 IST" "2015-01-01 02:00:00 IST"