-1

Whats the fastest way in R to find time difference: diff of row 1 to 2, 2 to 3, 3 to 4 and so on. Or timespan from 1 to 2, 2 to 3, ...

In the end I heading for a function that shows all diffs/timspans e.g. > 7000ms

HH:MM:SS:MIS* *Milliseconds 18:41:24.244 18:41:29.290 18:41:34.259 18:41:55.040 18:42:15.556 18:42:21.587 18:42:25.509 18:42:31.009 18:42:39.072 18:42:59.025 18:43:03.134 18:43:06.712 18:43:47.244 18:43:53.353 18:43:59.181 18:44:14.744 18:44:22.572 18:44:40.040 18:44:44.900 18:44:48.884 18:44:53.744 18:45:01.134 18:45:56.884 18:46:01.384 18:46:05.915 18:46:10.025 18:46:13.837 18:46:18.275 18:46:28.931 18:46:41.259 18:46:44.619 18:46:50.619

Teletubbi-OS X
  • 391
  • 1
  • 3
  • 13
  • You should find good hints here: http://stackoverflow.com/questions/12611361/r-find-time-difference-in-seconds-for-yyyy-mm-dd-hhmmss-mmm-format, and here: http://stackoverflow.com/questions/12649641/calculating-time-difference-in-r – Chase Nov 02 '14 at 20:00

2 Answers2

3

It's not clear what format your data is in to start with. I've imported it as a character vector:

head(times)
# [1] "18:41:24.244" "18:41:29.290" "18:41:34.259" "18:41:55.040" ...

Then, since you want differences, we can just prepend an arbitrary date and convert to POSIXct

times <- as.POSIXct(paste("2014-01-01",times),format="%Y-%m-%d %H:%M:%OS")
diff(times)
# Time differences in secs
# [1]  5.046  4.969 20.781 20.516  6.031  3.922  5.500  8.063 19.953  4.109 ...
jlhoward
  • 58,004
  • 7
  • 97
  • 140
3

Starting with the character vector x

head(x)
# [1] "18:41:24.244" "18:41:29.290" "18:41:34.259" "18:41:55.040"
# [5] "18:42:15.556" "18:42:21.587"

You can use strptime with diff

st <- strptime(x, "%H:%M:%OS")
st[diff(st) > 7]
#  [1] "2014-11-02 18:41:34.259 PST" "2014-11-02 18:41:55.040 PST"
#  [3] "2014-11-02 18:42:31.009 PST" "2014-11-02 18:42:39.072 PST"
#  [5] "2014-11-02 18:43:06.712 PST" "2014-11-02 18:43:59.181 PST"
#  [7] "2014-11-02 18:44:14.744 PST" "2014-11-02 18:44:22.572 PST"
#  [9] "2014-11-02 18:44:53.744 PST" "2014-11-02 18:45:01.134 PST"
# [11] "2014-11-02 18:46:18.275 PST" "2014-11-02 18:46:28.931 PST"
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245