I am trying to find the difference between the times people wake up and go to sleep from survey data. When I convert the data to a time so that I can use difftime, R doesn't recognise that values after 00:00 are from the next day.
Here is a sample of the data. Thanks in advance!
df <- data. Frame(
b = c('07:00', '10:00', '11:00', '13:00', '05:00'),
d = c('00:00', '00:30', '23:00', '22:00','04:20')
)
I have converted the characters to date times like so
df$b <- strptime(df$b, format = "%H:%M")
df$d <- strptime(df$d, format = "%H:%M")
but then I get stuck
Everything I have tried hasn't worked at all
CodePudding user response:
Use the modulo operator %%
as.numeric(df$Waking.up.time - df$Bed.time) %% (24 * 60)
# [1] 420 570 720 900 40
This code assumes that a person sleeps less than 24 hours.
CodePudding user response:
When the time difference is negative, add 1440 minutes (24 hours) to get the intended time difference.
df$Sleep <- ifelse(df$Waking.up.time - df$Bed.tim >= 0,
df$Waking.up.time - df$Bed.tim,
df$Waking.up.time - df$Bed.tim 1440)
df$Sleep
#> [1] 420 570 720 900 40
Edit: See Julien's answer for a more elegant solution.