Calculating Time Difference between two columns

旧城冷巷雨未停 提交于 2019-11-28 10:14:59

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

This was surprising and interesting find for me. If you are subtracting POSIXct objects you can use as.numeric to convert it into "hours", "minutes" etc.

For this example, see

CR_Date$hours <- as.numeric(CR_Date$pos2 - CR_Date$pos1, "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

Further exploring,

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

as.numeric(CR_Date$pos2 - CR_Date$pos1, "days")
#[1] 0.0000000 0.4270833
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!