计算两列之间的时差 [英] Calculating Time Difference between two columns

查看:76
本文介绍了计算两列之间的时差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在将因子转换为POSIXCT格式,然后应用datetime格式之后,我想计算2 pos1和pos2之间的datetime之差.

After converting factors in POSIXCT format and then applying datetime format, I want to take the difference of datetime between 2 pos1 and pos2.

但是,当我针对特定项目执行此操作时,我会在控制台中得到正确的答案,但是当我对整个操作集进行操作时,控制台只会输出数字,并且日期框架也会反映出这些数字,如您所见.

However, when I do that for a specific item I get the right answer in the console but when I do the operation on the whole set the console outputs just number and also the dateframe reflects those number as you can see.

当我尝试区别时如何获得数据框中的小时数? 我正在使用lubridate软件包,有什么功能吗?

How can I get the hours in the dataframe when I am trying to take the difference? I am using lubridate package, is there any function to do so?

这是RStudio中描述数据的示例代码/图片

Here is some example code/picture of the data in RStudio describing it

CR_Date <- data.frame(
  pos1="2014-07-01 00:00:00",
  pos2=c("2014-07-01 00:00:00","2014-07-01 10:15:00")
)
CR_Date[] <- lapply(CR_Date,as.POSIXct)
CR_Date

#        pos1                pos2
#1 2014-07-01 2014-07-01 00:00:00
#2 2014-07-01 2014-07-01 10:15:00

CR_Date$pos2[2] - CR_Date$pos1[2]
#Time difference of 10.25 hours
CR_Date$hours <- CR_Date$pos2 - CR_Date$pos1

推荐答案

首先,这与lubridate无关.

Firstly, this has nothing to do with lubridate.

第二,RStudio通过在显示窗口中打印变量来让您失望.如果在命令行窗口中输入CR_Date$hours,您会看到它打印出来

Secondly, RStudio has let you down by screwing with the printing of the variable in the display window. If you enter CR_Date$hours in the command line window you will see it prints

#Time differences in secs
#[1]     0 36900

head(CR_Date)给出:

#        pos1                pos2      hours
#1 2014-07-01 2014-07-01 00:00:00     0 secs
#2 2014-07-01 2014-07-01 10:15:00 36900 secs

其中任何一个都会提示您显示的内容.

Either of which would have tipped you off as to what it is displaying.

正如@Victorp所建议的,difftime是解决此问题的方法:

As @Victorp suggests, difftime is the way to resolve this:

CR_Date$hours <- with(CR_Date, difftime(pos2,pos1,units="hours") )
CR_Date

#        pos1                pos2       hours
#1 2014-07-01 2014-07-01 00:00:00  0.00 hours
#2 2014-07-01 2014-07-01 10:15:00 10.25 hours

这篇关于计算两列之间的时差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆