在 R 中查找时间差

Find difference between time in R

我想计算 "A" 和 "B" 的 R 时间差。我拥有的数据是个人入睡时的hour/minute/am-pm("A")和他们醒来的时间("B"):(df称为时间)

    Hour(A) Min(A) AMPM(A) Hour(B) Min(B) AMPM(B)
    1       30     AM      7       30     AM
    4       00     AM      9       00     AM
    11      30     PM      6       30     AM 

我一直在做一些研究,我发现我可以将时间创建为角色,然后将其更改为时间伴侣。

首先,我使用 unite() 函数 (tidyverse) 连接小时 (A) 和分钟 (A)。然后,我创建了另一个日期为 "fake" 的列(如果是下午:“2019-04-13”和“2019-04-14”)。然后,我再次使用函数 unite() 加入日期和时间,并使用函数 strptime() 将 class 更改为时间。

对于hour(B), min(B) 和AMPM(B),我也使用了函数unite 和join 三列。然后我应用函数 strptime() 将 class 更改为时间。

最后,我正在使用函数 difftime() 找出 A 和 B 之间的差异,但我不明白为什么我会得到异常结果。


time <- time %>% mutate(Date = ifelse(AMPM(A) == "  AM", "2019-04-14", "2019-04-13"))

time$Date <- as.Date(time$Date)

#Using unite to join Hour(A) with Mins(A) and Hour(B) with Mins(B)
time <- time %>% unite(Sleeptime,HourA,MinsA, sep = ":") %>% unite(Wakeuptime, HourB,MinsB, sep = ":") 

#Adding the seconds 
time$Sleeptime <- paste0(time$Sleeptime,":00")

#Using unite to join Hours(B)Mins(B) with AMPM(B)
time <- time %>% unite(Wakeuptime, Wakeuptime ,AMPMWake, sep = "" )

#Changing the class for time (B)
time$Wakeuptime2 <- strptime(x = paste0(time$Wakeuptime2, "m"), format = "%I:%M %p")

#Joining the fake date for (A) with the time(A)
time <- time %>% unite(ST, Date, Sleeptime, sep = " ")

#Changing the class for time (A)
time$ST = strptime(time$ST,format='%Y-%m-%d %H:%M:%S')

#Calculating the difference in time 
time$difference <- difftime(time$Wakeuptime2, time$ST, units = "hours")

我需要的是另一列以小时或分钟为单位的差异

    Hour(A) Min(A) AMPM(A) Hour(B) Min(B) AMPM(B) DIFF (min)
    1       30     AM      7       30     AM      300
    4       00     AM      9       00     AM      300
    11      30     PM      6       30     AM      420

我们可以用paste到assemble时间(A)和时间(B)的片段,然后转换as.POSIXct。从 bed-times 和 PM 我们减去 8.64e4 (一天以秒为单位)。现在很容易计算 apply 内的差异。

tmp <- sapply(list(1:3, 4:6), function(x) {
  cl <- as.POSIXct(apply(time[x], 1, paste, collapse=":"), format="%I:%M:%p")
  return(ifelse(time[tail(x, 1)] == "PM", cl - 8.64e4, cl))
  })
time <- cbind(time, `DIFF(min)`=apply(tmp, 1, diff)/60)
time
#   Hour(A) Min(A) AMPM(A) Hour(B) Min(B) AMPM(B) DIFF(min)
# 1       1     30      AM       7     30      AM       360
# 2       4      0      AM       9      0      AM       300
# 3      11     30      PM       6     30      AM       420

数据

time <- structure(list(`Hour(A)` = c(1L, 4L, 11L), `Min(A)` = c(30L, 
0L, 30L), `AMPM(A)` = c("AM", "AM", "PM"), `Hour(B)` = c(7L, 
9L, 6L), `Min(B)` = c(30L, 0L, 30L), `AMPM(B)` = c("AM", "AM", 
"AM")), row.names = c(NA, -3L), class = "data.frame")