我想减去POSIXct。我可以这样做,但取决于第一行(我猜?),差异将以秒或分钟为单位。下面你可以看到第一个差异以秒为单位,第二个差异以分钟为单位,因为我改变了第一行的时差:
#diff in seconds because 1st row time diff is small?
t1<- as.POSIXct(c("2015-02-02 20:18:03 00:00:00", "2015-02-02 20:17:02 00:00:00"),"GMT")
t2<- as.POSIXct(c("2015-02-02 20:18:02 00:00:00","2015-02-02 20:18:02 00:00:00"),"GMT")
d<-data.frame(t1= t1, t2= t2)
d$t1-d$t2
#diff in seconds because 1st row time diff is larger?
t1<- as.POSIXct(c("2015-02-02 20:13:03 00:00:00", "2015-02-02 20:17:02 00:00:00"),"GMT")
t2<- as.POSIXct(c("2015-02-02 20:18:02 00:00:00","2015-02-02 20:18:02 00:00:00"),"GMT")
d<-data.frame(t1= t1, t2= t2)
d$t1-d$t2
结果:
> #diff in seconds because 1st row time diff is small?
> t1<- as.POSIXct(c("2015-02-02 20:18:03 00:00:00", "2015-02-02 20:17:02 00:00:00"),"GMT")
> t2<- as.POSIXct(c("2015-02-02 20:18:02 00:00:00","2015-02-02 20:18:02 00:00:00"),"GMT")
> d<-data.frame(t1= t1, t2= t2)
> d$t1-d$t2
Time differences in secs
[1] 1 -60
>
>
> #diff in seconds because 1st row time diff is larger?
> t1<- as.POSIXct(c("2015-02-02 20:13:03 00:00:00", "2015-02-02 20:17:02 00:00:00"),"GMT")
> t2<- as.POSIXct(c("2015-02-02 20:18:02 00:00:00","2015-02-02 20:18:02 00:00:00"),"GMT")
> d<-data.frame(t1= t1, t2= t2)
> d$t1-d$t2
Time differences in mins
[1] -4.983333 -1.000000
无论第一行的差异是什么,我都希望能在几秒钟之内完成差异。有没有办法让这种情况发生?
谢谢。
答案 0 :(得分:30)
您可以使用difftime
作为建议,允许您指定测量单位,例如
difftime(t1, t2, units = "secs")
另一种方式(如同@nicola所述并出现在同一文档中)是利用-
具有-.POSIXt
方法的事实,并在减法操作后覆盖测量单位units<-
替换方法
res <- t1 - t2
units(res) <- "secs"