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

如何使用lubridate计算R中的时差,r,lubridate,R,Lubridate,我有两列包含时间值,我想插入第三列,用于计算其他两列中的时间差。我的结果总是出错。请帮忙! 下面是一个示例数据集 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

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

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
资料

资料


您需要给出它识别的类的
difftime
向量。比如说:

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$TOC
df$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

您需要给出它识别的类的
difftime
向量。比如说:

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$TOC
df$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