3

I have got a vector of POSIXct-data and want to calculate the difference between consecutive elements, like it is done by diff

e.g:

burst <- as.POSIXct(c("2016-11-07 17:20:52","2016-11-07 16:21:52", "2016-11-07 15:21:52", "2016-11-02 17:20:52","2016-11-02 16:21:52", "2016-11-02 15:21:52"))

conti <- as.POSIXct(c("2016-11-07 17:20:52","2016-11-06 17:20:52", "2016-11-05 17:20:52", "2016-11-04 17:20:52","2016-11-03 17:20:52", "2016-11-02 17:20:52"))

diff(burst)
diff(conti)

My problem is, that the units are not equal. I remember the function difftime which has got a parameter called unit but i am not able to construct a apply-function to get a simiral behaviour like in diff.

barracuda317
  • 608
  • 7
  • 24

1 Answers1

0

I'm not sure if there's a way to enforce particular units with diff for POSIXt objects. In case there isn't, you can work directly with the numerical values and then set the class and the units attribute so that you'll still have a difftime object with a units attribute.

For example, to get differences in minutes:

burst.diff = diff(as.numeric(burst))/60
burst.diff = as.difftime(burst.diff, units="mins")

burst.diff
Time differences in mins
[1]   -59   -60 -7141   -59   -60

If you don't care about maintaining the object class or units, then you can just do:

burst.diff = diff(as.numeric(burst))/60 

You could package this as a function. I'm not sure if this is the "right" way in terms of how I've handled class and attributes and I'd be interested to know if there are better ways to do this:

my_difftime = function(x, units="mins") {

  div = c("secs"=1, "mins"=60, "hours"=3600)

  if(is.na(match(units, names(div)))) {
    stop('Please specify either units as either "secs", "mins", or "hours"')
  } else {
    x = diff(as.numeric(x))/div[match(units, names(div))]
    as.difftime(x, units=units) 
  }
}

lapply(list(burst=burst, conti=conti), my_difftime, units="hours")
$burst
Time differences in hours
[1]   -0.9833333   -1.0000000 -119.0166667   -0.9833333   -1.0000000

$conti
Time differences in hours
[1] -24 -25 -24 -24 -24
eipi10
  • 91,525
  • 24
  • 209
  • 285