【发布时间】:2021-02-24 18:41:28
【问题描述】:
我的日期时间如下:
x = c("2015-09-12 03:52:00", "2017-06-15 21:37:28", "2017-04-08 20:44:11")
我想创建两个类别:如果时间在下午 6.30 到早上 8 点之间,我想返回“下班后”`,否则返回“下班后”。
我首先尝试通过提取时间部分来解决这个问题,但这会将其转换为一个字符,这意味着 ifelse 不起作用。
提前谢谢你。
【问题讨论】:
我的日期时间如下:
x = c("2015-09-12 03:52:00", "2017-06-15 21:37:28", "2017-04-08 20:44:11")
我想创建两个类别:如果时间在下午 6.30 到早上 8 点之间,我想返回“下班后”`,否则返回“下班后”。
我首先尝试通过提取时间部分来解决这个问题,但这会将其转换为一个字符,这意味着 ifelse 不起作用。
提前谢谢你。
【问题讨论】:
有点作弊,在 24 小时时钟上将 %H%M 转换为整数。
vec <- as.POSIXct(c("2015-09-12 03:52:00", "2017-06-15 21:37:28", "2017-04-08 20:44:11"))
hhmm <- as.integer(format(vec, format = "%H%M"))
ifelse(hhmm < 0800 | hhmm > 1830, "after-hours", "in-hours")
# [1] "after-hours" "after-hours" "after-hours"
类似,但使用十进制小时而不是假小时/分钟。
library(lubridate)
hhmm2 <- hour(vec) + minute(vec)/60
ifelse(hhmm2 < 8 | hhmm2 > 18.5, "after-hours", "in-hours")
# [1] "after-hours" "after-hours" "after-hours"
【讨论】:
times_as_char = c("2015-09-12 03:52:00", "2017-06-15 21:37:28", "2017-04-08 20:44:11")
# Converting character to date-time
times_as_datetimes <- lubridate::ymd_hms(times_as_char)
# We can use decimal hours to make time comparisons easier
times_as_hour_dec <- lubridate::hour(times_as_datetimes) +
lubridate::minute(times_as_datetimes)/60
time_status <- ifelse(times_as_hour_dec < 8 | times_as_hour_dec >= 18.5,
"after-hours",
"in hours")
【讨论】: