【问题标题】:Discretize a date-time variable to "in-hours" and "after-hours"将日期时间变量离散化为“in-hours”和“after-hours”
【发布时间】: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 不起作用。

提前谢谢你。

【问题讨论】:

    标签: r date lubridate


    【解决方案1】:

    基础 R

    有点作弊,在 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"
    

    【讨论】:

    • 谢谢@JonSpring,大错别字。
    • 谢谢@r2evans。现在开始了 R 在线课程,所以将来我应该知道这一切。
    【解决方案2】:
    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")
    

    【讨论】:

    • 非常感谢。对此,我真的非常感激。我只是运行它并且它工作。谢谢。
    猜你喜欢
    • 2014-07-16
    • 1970-01-01
    • 2023-01-24
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 2021-07-08
    • 2013-10-18
    • 2021-03-31
    相关资源
    最近更新 更多