Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

r - Calculating Time Difference between two columns

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

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...