Calculating Time Difference between two columns

为君一笑 提交于 2019-11-26 16:55:28

问题


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.

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?

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


回答1:


Firstly, this has nothing to do with lubridate.

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

and head(CR_Date) gives:

#        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.

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



回答2:


You may also use the "as.double method" and its units argument (see ?diffime):

as.double method [as.double(x, units = "auto", ...)] returns the numeric value expressed in the specified units

...where x is

an object inheriting from class "difftime"

Applied to your example, where pos2 - pos1 will result in a difftime object:

CR_Date$hours <- as.double(CR_Date$pos2 - CR_Date$pos1, units = "hours")
CR_Date

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

Or other units:

as.double(CR_Date$pos2 - CR_Date$pos1, units = "mins")
#[1]   0 615

as.double(CR_Date$pos2 - CR_Date$pos1, units = "days")
#[1] 0.0000000 0.4270833


来源:https://stackoverflow.com/questions/25033585/calculating-time-difference-between-two-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!