我正在尝试计算两列之间的时差
Time_1 Time_2
17:16:40 17:17:52
12:42:07 12:42:54
12:14:43 12:21:37
12:10:42 12:13:53
12:03:39 12:05:18
typeof(Time_1)
[1] "double"
typeof(Time_2)
[1] "double"
DF <- data.frame(Time_1, Time_2)
str(DF)
'data.frame': 5 obs. of 2 variables:
$ DF.Time_1: 'times' num NA 17:16:40 12:42:07 12:14:43 12:10:42 ...
..- attr(*, "format")= chr "h:m:s"
$ DF.Time_2: 'times' num NA 17:17:52 12:42:54 12:21:37 12:13:53 ...
..- attr(*, "format")= chr "h:m:s"
但是,当我尝试进行以下扣除时
DF$Diff <- (DF$Time_2 - Tbl$Time_1)
Diff列中的小数位数很小。
Time_1 Time_2 Diff
17:16:40 17:17:52 8.333333e-04
12:42:07 12:42:54 5.439815e-04
12:14:43 12:21:37 4.791667e-03
12:10:42 12:13:53 2.210648e-03
12:03:39 12:05:18 1.388889e-03
有人可以告诉我如何使Diff列以HH:MM:SS格式显示吗?
谢谢
答案 0 :(得分:0)
我们可以从times
转换为chron
,然后取差价
library(dplyr)
library(chron)
DF %>%
mutate_all(times) %>%
mutate(Diff = Time_2 - Time_1)
# Time_1 Time_2 Diff
#1 17:16:40 17:17:52 00:01:12
#2 12:42:07 12:42:54 00:00:47
#3 12:14:43 12:21:37 00:06:54
#4 12:10:42 12:13:53 00:03:11
#5 12:03:39 12:05:18 00:01:39
DF <- structure(list(Time_1 = c("17:16:40", "12:42:07", "12:14:43",
"12:10:42", "12:03:39"), Time_2 = c("17:17:52", "12:42:54", "12:21:37",
"12:13:53", "12:05:18")), class = "data.frame", row.names = c(NA,
-5L))