Why does the result show me time in days rather than time of day (ex. 23:09)

47 views Asked by At

I would like to know the mean of the sleep time but since there are times after midnight it seems to give me the mean as time in days, how would I be able to convert this to 24 hour time?

data <- read.table(text="
sleep_time wake_time
23:30:00 03:30:00
23:50:00 06:00:00
00:50:00 07:30:00
00:30:00 06:25:00
00:20:00 06:00:00
23:00:00 06:00:00
00:10:00 05:00:00
", header=T)

mean(times(data$wake_time))
# [1] 05:46:26

mean(times(data$sleep_time))
# [1] 10:18:34

wake <- times(data$wake_time)

sleep <- times(data$sleep_time)

times(mean(ifelse(sleep < wake, sleep + 1, sleep)))
# Time in days:
# [1] 1.000992
1

There are 1 answers

2
G. Grothendieck On

Assuming you are using the chron package then "times" objects are intended to represent the times in date/times as opposed to durations; however, we can get the effect anyways by extracting the days and times part separately and pasting them together. If tt is the result of the last line of code in the question and the objective is to display a string showing the number of days, hours:minutes:seconds then determine the number of days and create a string showing that and what remains after subtracting it off. (Note that this will round to the nearest second should there be fractions of a second.)

library(chron)

days <- as.integer(tt)
paste(days, tt - days)
## [1] "1 00:01:26"