如何在R中以小时为单位找到两个日期之间的差异? [英] How to find the difference between two dates in hours in R?
本文介绍了如何在R中以小时为单位找到两个日期之间的差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
冒着被问到显而易见的问题而被降低的极高风险,我如何找到两个小时中R中两个日期之间的差异?
At the extreme risk of being modded down for asking "obvious" questions, how do I find the difference between two dates in hours in R?
> ISOdate(2004,1,6) - ISOdate(2004,1,1)
Time difference of 5 days
> as.POSIXlt(ISOdate(2004,1,6) - ISOdate(2004,1,1))
Error in as.POSIXlt.default(ISOdate(2004, 1, 6) - ISOdate(2004, 1, 1)) :
do not know how to convert 'ISOdate(2004, 1, 6) - ISOdate(2004, 1, 1)' to class "POSIXlt"
> (ISOdate(2004,1,6) - ISOdate(2004,1,1))$year
Error in (ISOdate(2004, 1, 6) - ISOdate(2004, 1, 1))$year :
$ operator is invalid for atomic vectors
> (ISOdate(2004,1,6) - ISOdate(2004,1,1))$mon
Error in (ISOdate(2004, 1, 6) - ISOdate(2004, 1, 1))$mon :
$ operator is invalid for atomic vectors
推荐答案
使用函数 difftime
,并带有参数 units = hours
:
Use the function difftime
, with the argument units="hours"
:
x <- c(ISOdate(2004,1,6), ISOdate(2004,1,1))
difftime(x[1], x[2], units="hours")
Time difference of 120 hours
我怎么知道去哪里看?
How did I know where to look?
好吧,首先看一下您减去两次后得到的对象的结构:
Well, start by looking at the structure of the object you get when you subtract two times:
str(x[1] - x[2])
Class 'difftime' atomic [1:1] 5
..- attr(*, "units")= chr "days"
因此,现在您知道您正在处理 difftime
类。从这里很容易找到帮助:请参见?difftime
So now you know you are dealing with a class of difftime
. From here it's easy to find help: See ?difftime
这篇关于如何在R中以小时为单位找到两个日期之间的差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文