[英]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.在 POSIXCT 格式中转换因子然后应用日期时间格式后,我想取 2 pos1 和 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?我正在使用 lubridate 包,有什么功能可以这样做吗?
Here is some example code/picture of the data in RStudio describing it这是 RStudio 中描述它的数据的一些示例代码/图片
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
Firstly, this has nothing to do with lubridate.首先,这与lubridate无关。
Secondly, RStudio has let you down by screwing with the printing of the variable in the display window.其次,RStudio 通过在显示窗口中打印变量让您失望。 If you enter CR_Date$hours
in the command line window you will see it prints如果您在命令行窗口中输入CR_Date$hours
,您将看到它打印
#Time differences in secs
#[1] 0 36900
and head(CR_Date)
gives:和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.其中任何一个都会让您了解它所显示的内容。
As @Victorp suggests, difftime
is the way to resolve this:正如@Victorp 所建议的, difftime
是解决这个问题的方法:
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
You may also use the " as.double
method" and its units
argument (see ?diffime
):您也可以使用“ as.double
方法”及其units
参数(参见?diffime
):
as.double
method [as.double(x, units = "auto", ...)
] returns the numeric value expressed in the specified unitsas.double
方法 [as.double(x, units = "auto", ...)
] 返回以指定单位表示的数值
...where x
is ...其中x
是
an object inheriting from class
"difftime"
从类"difftime"
继承的对象
Applied to your example, where pos2 - pos1
will result in a difftime
object:应用于您的示例,其中pos2 - pos1
将导致difftime
对象:
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
:或其他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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.