【问题标题】:Convert decimal number double to hour, time, or difftime in R在 R 中将十进制数 double 转换为小时、时间或 difftime
【发布时间】:2017-09-13 14:02:11
【问题描述】:

我有一个指定一天中小时数的双精度向量,例如下面给出的示例。 6.50 将对应于 06:30 格式为 hh:mm 等等。

ts <- c(6.50, 7.00, 7.25, 7.45, 8.00)

我想将其转换为日期或时间格式。我可以想出的解决方案包括从数字中去除小数位并将它们转换为分钟,但这感觉有点“hacky”,例如

library(lubridate)
hm(paste(floor(ts), (ts - floor(ts)) * 60, sep = ':'))

肯定有更好的方法来做到这一点?

【问题讨论】:

    标签: r time lubridate


    【解决方案1】:

    试试这个:

    library(chron)
    
    times(ts / 24)
    ## [1] 06:30:00 07:00:00 07:15:00 07:27:00 08:00:00
    

    这也可以:

    library(chron)
    library(lubridate)
    
    hms(times(ts/24))
    ## [1] "6H 30M 0S" "7H 0M 0S"  "7H 15M 0S" "7H 27M 0S" "8H 0M 0S" 
    

    【讨论】:

    • 这个很好用,谢谢!很惊讶这不是更简单的 lubridate
    【解决方案2】:

    只支持lubridate

    library(lubridate)
    as.period(as.duration(days(x=1))*(ts/24))
    # "6H 30M 0S" "7H 0M 0S"  "7H 15M 0S" "7H 27M 0S" "8H 0M 0S"
    

    【讨论】:

    • 感谢您提供润滑方法!我遇到以下错误:Error in as.duration(days(x = 1)) : as.duration is not defined for class 'ordered'as.duration is not defined for class 'factor'?
    • 跑步会得到什么? days(x=1) output=[1] "1d 0H 0M 0S"as.duration(days(x=1)) output=[1] "86400s (~1 days)"
    • 啊,我们走了!命名空间与chron 冲突。这有效:as.period(as.duration(lubridate::days(x=1))*(ts/24))。再次感谢:)
    • 没问题...很高兴你知道了
    【解决方案3】:
    > lubridate::hm(ts)
    [1] "6H 50M 0S" "7H 0M 0S"  "7H 25M 0S" "7H 45M 0S" "8H 0M 0S"
    

    请求的替代方案(您的问题中已有的内容):

    > paste(floor(ts), round((ts-floor(ts))*60), sep=":")
    [1] "6:30" "7:0"  "7:15" "7:27" "8:0"
    

    【讨论】:

    • 感谢您的回答。请注意6.5 被转换为"6H 50M 0S",而不是"6H 30M 0S"。所以,不幸的是,这不是我想要的。
    • 好吧,在这种情况下,其他元素会相应更新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-12
    • 2016-05-09
    • 2016-06-01
    • 1970-01-01
    • 2013-11-12
    相关资源
    最近更新 更多