在R中将十进制数字double转换为小时,时间或difftime
我有一个指定一天中的小时的双精度矢量,例如下面给出的示例。 6.50
将对应于06:30
的hh:mm
格式等。在R中将十进制数字double转换为小时,时间或difftime
ts <- c(6.50, 7.00, 7.25, 7.45, 8.00)
我想将其转换为日期或时间格式。我能想出的解决方案涉及从数字中除去小数位并将其转换为分钟,但是这感觉有点“黑客”,例如,
library(lubridate)
hm(paste(floor(ts), (ts - floor(ts)) * 60, sep = ':'))
当然有更好的方法来做到这一点?
试试这个:
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::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"
坚持只与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"
谢谢你提供lubridate方法!我遇到了以下错误:'as.duration(days(x = 1))中的错误:as.duration没有为'ordered'类定义.duration没有为class'factor''定义? – JanLauGe
如果你跑步,你会得到什么? (days(x = 1))'output ='[1]“86400s(〜1 days)''days(x = 1)'output ='[1]”1d 0H 0M 0S“'''' – CPak
啊,我们走吧!命名空间与'chron'冲突。这工作:'as.period(as.duration(lubridate :: days(x = 1))*(ts/24))''。再次感谢:) – JanLauGe
这个效果很好,谢谢! 惊讶这不是更简单与lubridate – JanLauGe