I have a series of duration that range up to 118 hours in a format like so "118:34:42" where 118 is hours, 34 is minutes, and 42 is seconds. Output should be a number of seconds.
I would like to convert this to some kind of time type in R, but most of the libraries I've looked at want to add a date (lubridate, zoo, xts), or return "NA" due to the hours being beyond a 24 hour range. I could parse the string and return a number of seconds, but I'm wondering if there's a faster way.
I'm slightly new to R (maybe 3 months in to working with this).
Any help figuring out how to deal with this would be appreciated.
Example:
library(lubridate)
x <- c("118:34:42", "114:12:12")
tt <- hms(x)
Error in parse_date_time(hms, orders, truncated = truncated, quiet = TRUE) :
No formats could be infered from the training set.
#try another route
w <- "118:34:42"
tt2 <- hms(w)
tt2
#[1] NA
z <- "7:02:02"
tt3 <- hmw(z)
tt3
#[1] "7H 2M 2S"
In the lubridate
package there is a function hms()
that returns a time object:
library(lubridate)
x <- c("118:34:42", "114:12:12")
tt <- hms(x)
tt
[1] 118 hours, 34 minutes and 42 seconds
[2] 114 hours, 12 minutes and 12 seconds
The function hms()
returns an object of class Period
:
str(tt)
Formal class 'Period' [package "lubridate"] with 6 slots
..@ .Data : num [1:2] 42 12
..@ year : num [1:2] 0 0
..@ month : num [1:2] 0 0
..@ day : num [1:2] 0 0
..@ hour : num [1:2] 118 114
..@ minute: num [1:2] 34 12
You can do arithmetic using these objects. For example:
tt[2] - tt[1]
[1] -4 hours, -22 minutes and -30 seconds
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With