【问题标题】:How to convert a time interval saved as an integer to a date object in R?如何将保存为整数的时间间隔转换为 R 中的日期对象?
【发布时间】:2019-11-04 05:47:50
【问题描述】:

我有一个带有整数变量的数据集,它表示在一整天中以 5 分钟为间隔进行的观察,但是当它计数到 55 时,它会增加小时。所以跟随“55”是“100”,然后是“105”......并且跟随“955”是“1000”。本质上它是一个 hh:mm 24 小时制,但省略了前面的零。我需要将这些转换为时间对象,但在 lubridate 包中没有找到简单的函数。

我最后的手段是将此变量转换为字符串,使用“if”循环将 3、2 或 1 个零粘贴到每个零上,这样我就可以调用 parse_date_time(data$interval, "H!M!" ) 但我想知道是否有一个我不知道的更优雅的解决方案?

【问题讨论】:

    标签: r


    【解决方案1】:

    使用sprintf将整数转化为定宽字符串,再转化为时间对象。

    x <- c(50, 55, 100, 105, 955, 1000)
    as.POSIXct(sprintf("%04d", x), format = "%H%M", tz = "UTC")
    
    #[1] "2019-11-04 00:50:00 UTC" "2019-11-04 00:55:00 UTC" "2019-11-04 01:00:00 UTC"
    #[4] "2019-11-04 01:05:00 UTC" "2019-11-04 09:55:00 UTC" "2019-11-04 10:00:00 UTC"
    

    stringr::str_padstrptime 也可以获得类似的结果

    strptime(stringr::str_pad(x, 4, pad = 0), format = "%H%M", tz = "UTC")
    

    或使用parse_date_time

    lubridate::parse_date_time(sprintf("%04d", x), "HM")
    

    【讨论】:

      猜你喜欢
      • 2021-05-16
      • 1970-01-01
      • 2018-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-28
      • 2023-03-11
      • 1970-01-01
      相关资源
      最近更新 更多