Search code examples
rtimelapplyposixct

Given the time in hh:mm:ss format, compute the number of seconds using base R


I have a character object with the time in hh:mm:ss-like format.

A given vector a for example purposes:

[1] "01|15|59" "1|47|16"  "01|17|20" "1|32|34"  "2|17|17" 

I want to compute the number of seconds for each measurement.

For the first one you can simply do:

a <-  as.numeric(strsplit(a, "|", fixed=TRUE)[[1]])
a[1]*60*60 + a[2]*60 + a[3]

I could use a loop to iterate through all of the elements of the char object, but ideally I would like to use an apply function. Not sure how to implement it.


Solution

  • You can use sapply():

    sapply(strsplit(a, "\\|"), \(x) sum(as.numeric(x) * 60^(2:0)))
    # [1] 4559 6436 4640 5554 8237
    

    or convert the time string to POSIXct and pass it to as.numeric() to get seconds:

    as.numeric(strptime(paste('1970-01-01', a), '%F %H|%M|%S', 'UTC'))
    # [1] 4559 6436 4640 5554 8237
    
    difftime(strptime(a, '%H|%M|%S', 'UTC'), Sys.Date(), units = 'sec')
    # Time differences in secs
    # [1] 4559 6436 4640 5554 8237
    

    Data
    a <- c("01|15|59", "1|47|16", "01|17|20", "1|32|34", "2|17|17")