如何使用 lubridate 计算 R 中的时差

How to use lubridate to compute time difference in R

我有两列包含时间值,我想插入第三列来计算其他两列中的时间差。我的结果不断出错。请帮忙! 下面是一个示例数据集

TOC         ORD
00:11:02    00:12:48
00:11:36    00:18:39
00:16:48    00:19:33
00:18:31    00:26:31
00:25:17    00:28:43
00:29:24    00:34:49
00:31:25    00:36:35
00:35:54    00:55:09
00:39:35    00:41:43
00:47:07    01:17:44
01:05:11    01:10:34
01:07:27    01:23:45
01:38:38    01:40:27

数据 screenshOt

数据

library(lubridate)
CR_Date1 <- with(CR_Date, difftime(as.numeric(EXP_DAFB2012$TOC, 
EXP_DAFB2012$ORD)))
CR_Date1

R 的输出

Error in as.POSIXct.numeric(time1) : 'origin' must be supplied

In as.POSIXct(time1) : NAs introduced by coercion
In addition: Warning message:
  as.difftime.EXP_DAFB2012.TOC..EXP_DAFB2012.ORD..4
1                                               NA secs
2                                               NA secs
3                                               NA secs
4                                               NA secs
5                                               NA secs
6                                               NA secs
7                                               NA secs
8                                               NA secs

您需要提供 difftime 它识别的 class 向量。所以,像这样:

difftime(as.POSIXct(df$ORD, format = "%H:%M:%S"), as.POSIXct(df$TOC, format = "%H:%M:%S"))

结果:

Time differences in mins
 [1]  1.766667  7.050000  2.750000  8.000000  3.433333  5.416667  5.166667 19.250000  2.133333 30.616667  5.383333 16.300000  1.816667

此代码假定 df$TOCdf$ORD 是字符串,而不是因子。如果它们是因子,则可以将 as.POSIXct 部分嵌套在 as.character 中。您可以在 difftime 中使用 units 来更改输出的单位。例如:

> difftime(as.POSIXct(df$ORD, format = "%H:%M:%S"), as.POSIXct(df$TOC, format = "%H:%M:%S"),
    unit = "hours")
Time differences in hours
 [1] 0.02944444 0.11750000 0.04583333 0.13333333 0.05722222 0.09027778 0.08611111 0.32083333 0.03555556 0.51027778 0.08972222 0.27166667 0.03027778