简体   繁体   English

如何找到R中两个小时之间的差异?

[英]How to find the difference between two dates in hours in 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? 由于被问到“明显”问题而被降低风险的极大风险,如何找到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

Use the function difftime , with the argument units="hours" : 使用函数difftime ,参数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"

So now you know you are dealing with a class of difftime . 所以现在你知道你正在处理一类difftime From here it's easy to find help: See ?difftime 从这里可以很容易地找到帮助:参见?difftime

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM