处理R中的5分钟30秒等时间段 [英] Dealing with time-periods such as 5 minutes and 30 seconds in R
问题描述
在R中是否有一种很好的方法来处理诸如05:30(5分钟30秒)之类的时间段?
Is there a good way to deal with time periods such as 05:30 (5 minutes, 30 seconds) in R?
或者,仅用几秒钟即可将其转换为整数的最快方法是什么?
Alternatively what's the fastest way to convert it into an integer with just seconds?
我只能转换为日期,而不能真正找到时间的数据类型.
I can only convert to dates and can't really find a data type for time.
我在动物园中使用R.
非常感谢!
秒是处理此问题的最佳方法.我将以下Shane的代码进行了调整以满足自己的目的,这就是结果.
Seconds was the best way to deal with this. I adapted Shane's code below to my purposes, here's the result.
# time - time in the format of dd hh:mm:ss
# (That's the format used in cvs export from Alcatel CCS reports)
#
time.to.seconds <- function(time) {
t <- strsplit(as.character(time), " |:")[[1]]
seconds <- NaN
if (length(t) == 1 )
seconds <- as.numeric(t[1])
else if (length(t) == 2)
seconds <- as.numeric(t[1]) * 60 + as.numeric(t[2])
else if (length(t) == 3)
seconds <- (as.numeric(t[1]) * 60 * 60
+ as.numeric(t[2]) * 60 + as.numeric(t[3]))
else if (length(t) == 4)
seconds <- (as.numeric(t[1]) * 24 * 60 * 60 +
as.numeric(t[2]) * 60 * 60 + as.numeric(t[3]) * 60 +
as.numeric(t[4]))
return(seconds)
}
推荐答案
正如Dirk指出的那样,存在一个名为"difftime"的对象,但是无法添加/减去该对象.
As Dirk points out, there is an object called "difftime", but it can't be added/subtracted.
> as.difftime(5, units="mins")
Time difference of 5 mins
> d <- seq(from=as.POSIXct("2003-01-01"), to=as.POSIXct("2003-01-04"), by="days")
> d
[1] "2003-01-01 GMT" "2003-01-02 GMT" "2003-01-03 GMT" "2003-01-04 GMT"
> d + as.difftime(5, units="mins")
[1] "2003-01-01 00:00:05 GMT" "2003-01-02 00:00:05 GMT"
[3] "2003-01-03 00:00:05 GMT" "2003-01-04 00:00:05 GMT"
Warning message:
Incompatible methods ("+.POSIXt", "Ops.difftime") for "+"
似乎您现在可以执行此操作:
Seems you can now do this:
> as.difftime(5, units='mins')
Time difference of 5 mins
> d <- seq(from=as.POSIXct("2003-01-01"), to=as.POSIXct("2003-01-04"), by="days")
> d
[1] "2003-01-01 GMT" "2003-01-02 GMT" "2003-01-03 GMT" "2003-01-04 GMT"
> d + as.difftime(5, unit='mins')
[1] "2003-01-01 00:05:00 GMT" "2003-01-02 00:05:00 GMT"
[3] "2003-01-03 00:05:00 GMT" "2003-01-04 00:05:00 GMT"
> d + as.difftime(5, unit='secs')
[1] "2003-01-01 00:00:05 GMT" "2003-01-02 00:00:05 GMT"
[3] "2003-01-03 00:00:05 GMT" "2003-01-04 00:00:05 GMT"
>
这与最近发布的R 2.15.0一起
This is with the recently released R 2.15.0
这篇关于处理R中的5分钟30秒等时间段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!