Reputation: 21
I want to calculate the amount of time someone spends in bed at night. First column, j1bed (time goes to bed):
dput(head(subscales$j1bed, 20))
c("23:00:00", "01:00:00", "22:00:00", "00:00:00", "00:00:00",
"23:00:00", "03:00:00", "23:00:00", "22:00:00", "23:00:00", "21:00:00",
"23:30:00", "22:00:00", "22:00:00", "20:00:00", "22:00:00", "22:00:00",
"21:00:00", "20:00:00", "23:00:00")
Second column, j3wake (time wakes up):
dput(head(subscales$j3wake, 20))
c("08:00:00", "08:00:00", "05:00:00", "08:00:00", "07:00:00",
"07:00:00", "09:00:00", "09:00:00", "08:00:00", "06:00:00", "03:00:00",
"08:30:00", "07:00:00", "08:00:00", "09:00:00", "07:00:00", "06:00:00",
"07:00:00", "07:00:00", "12:00:00")
My code currently is as follows:
Hours_in_Bed<- as.numeric(difftime(strptime(subscales$j3wake, "%I:%M %p" ),strptime(subscales$j1bed, "%I:%M %p" ),units='hours'))
For some reason, this is coming up with only "NA". Any ideas?
Edit: I've tried the following three suggestions: 1)
result1<-strptime(subscales$j3wake, "%I:%M %p")
result2<-strptime(subscales$j1bed, "%I:%M %p")
Hours_in_Bed<-as.numeric(difftime(result2, result1, units='hours'))
This yields only "NA"s. 2)
subscales$j3wake1=as.POSIXct(paste('1970-1-1',subscales$j3wake))
subscales$j1bed1 =as.POSIXct(paste('1970-1-1',subscales$j1bed))
as.numeric(difftime(subscales$j1bed1,subscales$j3wake1,units='hours'))
This yields "0"s. 3)
all(grepl("[0-9]{2}:[0-9]{2} (AM|PM)", subscales$j3wake))
all(grepl("[0-9]{2}:[0-9]{2} (AM|PM)", subscales$j1bed))
Both yield "False".
Edit 2: that last tip was key! I think I should be using "%H:%M" instead:
Hours_in_Bed<- as.numeric(difftime(strptime(subscales$j3wake, "%H:%M" ),strptime(subscales$j1bed, "%H:%M" ),units='hours'))
If I then do:
Hours_in_Bed[!is.na(Hours_in_Bed) & Hours_in_Bed<0] <- 24 + Hours_in_Bed[!is.na(Hours_in_Bed) & Hours_in_Bed<0]
I should be good to go. Let me know if I'm still off, and thanks for the help!
Upvotes: 1
Views: 53
Reputation: 4340
It's usually easier to use the POSIXct-type even if there isn't any real year/month/day. Example:
subscales$j3wake1 = as.POSIXct(paste('1970-1-1',subscales$j3wake))
subscales$j1bed1 = as.POSIXct(paste('1970-1-1',subscales$j1bed))
as.numeric(difftime(subscales$j1bed1,subscales$j3wake1,units='hours'))
Upvotes: 1