简体   繁体   English

从另一个时间减去一个时间列

[英]Subtracting one time column from another r

I'm trying to work out the time differences between two columns 我正在尝试计算两列之间的时差

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"

BUT, when I try to conduct the following subtraction 但是,当我尝试进行以下减法时

DF$Diff <- (DF$Time_2 - Tbl$Time_1)

I get very small decimals in the Diff column. 我在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

Can anyone tell me how I could get the Diff column to show in format HH:MM:SS? 谁能告诉我如何使Diff列以HH:MM:SS格式显示?

Thanks 谢谢

We can convert to times from chron and then take the difference 我们可以从chron转换为times ,然后求差

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

data 数据

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))

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

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