r - 具有自定义开始时间的地板日期时间(润滑)
问题描述
有没有办法使用自定义开始时间而不是最早的时间来确定日期?
例如,从上午 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"
解决方案
您可以编写一个小程序switch
(lubridate
尽管没有)。
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"
推荐阅读
- arrays - 用可编码的方式解码 JSON 数组 - Swift 5
- scala - Http4s 客户端以递归方式将实体编码为 x-www-form-urlencoded
- python - 如何找到随机数生成器的种子?
- javascript - Javascript 中的无分配抽象
- reactjs - 如何使用 React Hooks 向用户显示特定的 http 响应代码和消息
- pdf - 像“f_f”、“uni00D0”和“a204”这样的命名pdf字符在哪里定义?
- postgresql - 如何在 Ubuntu 20.04 的 pgadmin 4 中设置邮件和密码
- reactjs - 如何让反应将自定义钩子的返回值视为稳定的身份?
- sql - 显示最新更新的数据
- typescript - NLS localize 的第一个参数指的是什么?