Reputation: 409
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
Upvotes: 4
Views: 1245
Reputation: 43354
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
Upvotes: 3
Reputation: 20095
You can use lubridate
package. The hms
function will convert time from characters to HMS
format. Then use seconds
to convert to seconds and calculate mean/sd
. Finally, use seconds_to_period
to get the result in HMS
format.
library(lubridate)
Col_Time = c('03:08:20','03:11:30','03:22:18','03:27:39')
#Get the mean
seconds_to_period(mean(seconds(hms(Col_Time))))
# [1] "3H 17M 26.75S"
#Get the sd
seconds_to_period(sd(seconds(hms(Col_Time))))
#[1] "9M 3.40983612739285S"
Upvotes: 1