将日期时间变量离散化为“小时".和“下班后" [英] Discretize a date-time variable to "in-hours" and "after-hours"

查看:55
本文介绍了将日期时间变量离散化为“小时".和“下班后"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类似的日期时间:

x = c("2015-09-12 03:52:00", "2017-06-15 21:37:28", "2017-04-08 20:44:11") 

我想创建两个类别:如果时间在6.30pm到8am之间,我想返回"after-hours",否则返回"in-hours".

I want to create two categories: If the time is between 6.30pm and 8 am I want to return "after-hours"`, otherwise it returns "in-hours".

我试图通过提取时间部分来解决此问题,但是将其转换为一个字符,这意味着 ifelse 无法正常工作.

I tried to solve this first by extracting the time part, but that converted it to a character which meant, ifelse was not working.

谢谢.

推荐答案

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

这篇关于将日期时间变量离散化为“小时".和“下班后"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆