Search code examples
rchron

standard deviation of time in a column in hr:min:sec format


In the question "average time in a column in hr:min:sec format" the following example is given:

Col_Time = c('03:08:20','03:11:30','03:22:18','03:27:39')
library(chron)
mean(times(Col_Time))
[1] 03:17:27

How can I get hr:min:sec as result for the standard deviation? If I use the R function sd, the result looks like that:

sd(times(Col_Time))
[1] 0.006289466

Solution

  • sd is operating on the number internally representing the time (days for chron::times, seconds for hms and POSIXct, settable for difftime), which is fine. The only problem is that it is dropping the class from the result so it isn't printed nicely. The solution, then, is just to convert back to the time class afterwards:

    x <- c('03:08:20','03:11:30','03:22:18','03:27:39')
    
    chron::times(sd(chron::times(x)))
    #> [1] 00:09:03
    
    hms::as.hms(sd(hms::as.hms(x)))
    #> 00:09:03.409836
    
    as.POSIXct(sd(as.POSIXct(x, format = '%H:%M:%S')), 
               tz = 'UTC', origin = '1970-01-01')
    #> [1] "1970-01-01 00:09:03 UTC"
    
    as.difftime(sd(as.difftime(x, units = 'secs')), 
                units = 'secs')
    #> Time difference of 543.4098 secs