我有两列包含时间值,我想插入第三列,计算其他两列中时间之间的差异。我的结果一直都是错误的。请帮忙! 以下是DATASET示例
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
DATA screenshOt
DATA
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
答案 0 :(得分:3)
您需要提供它识别的类的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
中。您可以在units
中使用difftime
来更改输出的单位。例如:
> 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