简体   繁体   English

R 中的减法时间

[英]Substracting time in R

I want to calculate the amount of time someone spends in bed at night.我想计算一个人晚上在床上花费的时间。 First column, j1bed (time goes to bed):第一列,j1bed(睡觉时间):

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):第二列,j3wake(时间唤醒):

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".出于某种原因,这只是提出了“NA”。 Any ideas?有任何想法吗?

Edit: I've tried the following three suggestions: 1)编辑:我尝试了以下三个建议: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.这仅产生“NA”。 2) 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.这产生“0”。 3) 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:编辑 2:最后一个提示是关键:我认为我应该使用 "%H:%M" 代替:

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.我应该对 go 好。 Let me know if I'm still off, and thanks for the help!让我知道我是否仍然关闭,并感谢您的帮助!

It's usually easier to use the POSIXct-type even if there isn't any real year/month/day.即使没有任何真正的年/月/日,通常也更容易使用 POSIXct 类型。 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'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM