r:如何将 hh:mm:s 中的持续时间计算为以小时为单位但与午夜重叠的固定时间
r: How to calculate duration in hh:mm:s to a fixed time in hours but overlapping midnight
我在 df$times
中定义了以下 hh:mm:ss
times
1 22:55:00
2 01:05:00
3 21:00:00
我想计算从 20:00:00
到每个时间的持续时间。但是,有些时间是在午夜之后,在这种情况下,持续时间应估计为 20:00:00
“第二天”
预期输出
times new
1 22:55:00 2.92
2 01:05:00 5.08
3 21:00:00 -1.00
数据
df <- structure(list(times = c("22:55:00", "01:05:00", "21:00:00")), class = "data.frame", row.names = c(NA,
-3L))
我们用 hms
转换为期间 class,创建一个条件来检查比较的时间值是否大于 'times',然后加上 1 天并减去,否则只是减
library(dplyr)
library(lubridate)
df %>%
mutate(times1 = hms(times), times2 = hms("20:00:00"),
new = as.numeric(case_when(times1 < times2 ~
(times1 + hms("24:00:00") - times2), TRUE ~ times2- times1))/3600 ) %>%
select(times, new)
# times new
#1 22:55:00 -2.916667
#2 01:05:00 5.083333
#3 21:00:00 -1.000000
library(dplyr)
library(data.table)
mydf <- structure(list(times = c("22:55:00", "01:05:00", "21:00:00")), class = "data.frame", row.names = c(NA,
-3L))
mydf %>%
mutate(
times = as.ITime(times),
difference = case_when (
times > as.ITime("20:00:00") ~ difftime(times, as.ITime("20:00:00")),
TRUE ~ difftime(as.ITime("23:59:59"), as.ITime("19:59:59"))
+ difftime( times, as.ITime("00:00:01"))
)
)
我在 df$times
hh:mm:ss
times
1 22:55:00
2 01:05:00
3 21:00:00
我想计算从 20:00:00
到每个时间的持续时间。但是,有些时间是在午夜之后,在这种情况下,持续时间应估计为 20:00:00
“第二天”
预期输出
times new
1 22:55:00 2.92
2 01:05:00 5.08
3 21:00:00 -1.00
数据
df <- structure(list(times = c("22:55:00", "01:05:00", "21:00:00")), class = "data.frame", row.names = c(NA,
-3L))
我们用 hms
转换为期间 class,创建一个条件来检查比较的时间值是否大于 'times',然后加上 1 天并减去,否则只是减
library(dplyr)
library(lubridate)
df %>%
mutate(times1 = hms(times), times2 = hms("20:00:00"),
new = as.numeric(case_when(times1 < times2 ~
(times1 + hms("24:00:00") - times2), TRUE ~ times2- times1))/3600 ) %>%
select(times, new)
# times new
#1 22:55:00 -2.916667
#2 01:05:00 5.083333
#3 21:00:00 -1.000000
library(dplyr)
library(data.table)
mydf <- structure(list(times = c("22:55:00", "01:05:00", "21:00:00")), class = "data.frame", row.names = c(NA,
-3L))
mydf %>%
mutate(
times = as.ITime(times),
difference = case_when (
times > as.ITime("20:00:00") ~ difftime(times, as.ITime("20:00:00")),
TRUE ~ difftime(as.ITime("23:59:59"), as.ITime("19:59:59"))
+ difftime( times, as.ITime("00:00:01"))
)
)