r - how to find time difference from row names? -


i have data frame object row names time stamps. "size" variable far.

                           size 2008-01-14 09:29:49         0 2008-01-14 09:29:59         0 2008-01-14 09:29:59.1       0 2008-01-14 09:30:00        842 2008-01-14 09:30:00.1      34 2008-01-14 09:30:00.2       1 2008-01-14 09:30:00.3       1 2008-01-14 09:30:00.4       1 2008-01-14 09:30:00.5       1 2008-01-14 09:30:02        38 

i create new column shows time difference previous row. time difference first row can blank.

                        size  dtime 2008-01-14 09:29:49      0     na 2008-01-14 09:29:59      0     10  2008-01-14 09:29:59.1    0     0.1 2008-01-14 09:30:00    842     0.9 2008-01-14 09:30:00.1   34     0.1 2008-01-14 09:30:00.2    1     0.1 2008-01-14 09:30:00.3    1     0.1 2008-01-14 09:30:00.4    1     0.1 2008-01-14 09:30:00.5    1     0.1 2008-01-14 09:30:02     38     1.5 

i trying use loop solve like:

file<-as.data.frame(mtq) l<-nrow(file) file$dtime<-na (f in 2:l){    file$dtime[f]<-difftime(row.names(file)[f], row.names(file)[f-1]) } 

it has error of "replacement has 12853 rows, data has 12852"

would please give me advice?

thank you

you use diff after converting posixct. length of diff output 1 less than nrow of dataset. so, can append na @ beginning.

 df1$dtime <- c(na,round(diff(as.posixct(row.names(df1))),1))  df1  #                      size dtime  #2008-01-14 09:29:49      0    na  #2008-01-14 09:29:59      0  10.0  #2008-01-14 09:29:59.1    0   0.1  #2008-01-14 09:30:00    842   0.9  #2008-01-14 09:30:00.1   34   0.1  #2008-01-14 09:30:00.2    1   0.1  #2008-01-14 09:30:00.3    1   0.1  #2008-01-14 09:30:00.4    1   0.1  #2008-01-14 09:30:00.5    1   0.1  #2008-01-14 09:30:02     38   1.5 

or

 v1 <- as.posixct(row.names(df1))  df1$dtime <- round(v1-lag(v1),1) 

Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -