Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Work with durations over 24 hours in R

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"
like image 329
alplv Avatar asked Dec 21 '12 06:12

alplv


1 Answers

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 
like image 69
Andrie Avatar answered Oct 20 '22 07:10

Andrie