使用疏水性计算R中的时间差 [英] Calculating Time Difference in R using lubridate
问题描述
在转换POSIXCT格式的因子然后应用日期时间格式之后,我想要采用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
这篇关于使用疏水性计算R中的时间差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!