我想减去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
我希望差异总是以秒为单位,无论第一行的差异是什么。有办法让这一切发生吗?
谢谢。
您可以在提案中使用difftime
,它允许您指定度量单位,例如
difftime(t1, t2, units = "secs")
另一种方法(如@nicola所提到的,并存在于同一文档中)是利用-
具有-.POSIXt
方法的事实,并在使用units<-
替代方法进行减法操作后覆盖测量单元
res <- t1 - t2
units(res) <- "secs"