1

There is a similar question I have come across to mine on this page:

Date-time differences between rows in R

Here is a very small snippet of my data:

DT  
29/07/12 20:05:01   
29/07/12 20:20:59   
30/07/12 02:42:08 
30/07/12 02:53:17 
30/07/12 02:53:18 
30/07/12 02:53:19 

I would like to do the same thing as this person asked ie calculate time differences (delta time) in R between subsequent rows. The timestamps are stored in a data frame with time as date-time (day/month/year hour:min:sec).

This code was kindly suggested and works most the time, apart from when the time intervals break across days, and then I get huge incorrect numbers (such as 31472469 seconds between 29/07/12 20:20:59 and 30/07/12 02:42:08.

c_time <- as.POSIXlt( mydf$c_time )
c_time <- rev( c_time )
difftime(c_time[1:(length(c_time)-1)] , c_time[2:length(c_time)])

Does anyone have any suggestions?

Thanks!

Community
  • 1
  • 1
Noosentin
  • 71
  • 9

1 Answers1

0

It is better to be explicit with the format otherwise you have to read really carefully what happens in the default option:

mydf <- read.table(text="c_time
29/07/12 20:05:01  
29/07/12 20:20:59  
30/07/12 02:42:08
30/07/12 02:53:17
30/07/12 02:53:18
30/07/12 02:53:19", sep=",", row.names=NULL, header=T)
c_time <- as.POSIXlt( mydf$c_time, format="%d/%m/%y %H:%M:%S")
c_time <- rev( c_time )
difftime(c_time[1:(length(c_time)-1)] , c_time[2:length(c_time)])

##Time differences in secs
##[1]     1     1   669 22869   958
chinsoon12
  • 25,005
  • 4
  • 25
  • 35