gpt4 book ai didi

r - 减去POSIXct时如何以相同单位表示时差

转载 作者:行者123 更新时间:2023-12-03 15:18:59 25 4
gpt4 key购买 nike

我想减去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"

关于r - 减去POSIXct时如何以相同单位表示时差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30510044/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com