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.
I'm using R with zoo.
Thanks a lot !
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)
}
As Dirk points out, there is an object called "difftime", but it can't be added/subtracted.
Seems you can now do this:
This is with the recently released R 2.15.0
Yes, while there is no 'time' type, you can use an offset time:
When you use the zoo package, you are using standard
POSIXt
types for your times indices. Both zoo and the newer and also highly-recommended xts package can usePOSIXt
, and especially the compactPOSIXct
type, for indexing.The xts package has a lot more indexing functionality, and Jeff recently added parsing of intervals according to the ISO8601-2004(e) specification and gives these references for ISO8601 and a FAQ for widely used standars for date and time formats. To use this xts version, you may need to switch the the xts development snapshot on r-forge
[Edit:] Also, regarding the question on 'conversion': this is easy once you have objects of class POSIXt / POSIXct as
as.numeric()
will convert POSIXct to (fractional) seconds since the epoch. R goes further than the POSIX standard and uses a double here, so you get millisecond precision:and