首页 > 解决方案 > 具有自定义开始时间的地板日期时间(润滑)

问题描述

有没有办法使用自定义开始时间而不是最早的时间来确定日期?

例如,从上午 8 点和下午 8 点开始,而不是上午 12 点和下午 12 点,将一天中的地板时间分成 2 个 12 小时间隔。

例子:

x <- ymd_hms("2009-08-03 21:00:00")
y <- ymd_hms("2009-08-03 09:00:00")
floor_date(x, '12 hours')
floor_date(y, '12 hours')

# default lubridate output:
[1] "2009-08-03 12:00:00 UTC"
[1] "2009-08-03 UTC"

# what i would like to have:
[1] "2009-08-03 20:00:00 UTC"
[1] "2009-08-03 08:00:00 UTC"


标签: rdatetimelubridate

解决方案


您可以编写一个小程序switchlubridate尽管没有)。

FUN <- function(x) {
  s <- switch(which.min(abs(mapply(`-`, c(8, 20), as.numeric(substr(x, 12, 13))))), 
              "08:00:00", "20:00:00")
  as.POSIXct(paste(as.Date(x), s))
}
FUN("2009-08-03 21:00:00")
# [1] "2009-08-03 20:00:00 CEST"

FUN("2009-08-03 09:00:00")
# [1] "2009-08-03 08:00:00 CEST"

推荐阅读