Date-time differences between rows in R

后端 未结 2 2113
不思量自难忘°
不思量自难忘° 2020-12-06 17:44

I would like to calculate time differences (delta time) in R. The timestamps are stored in a two-column data frame with time as date-time (year-month-day hour:min: sec.msec)

2条回答
  •  春和景丽
    2020-12-06 18:29

    Try this (I am assuming that you have your data in a data.frame called mydf) and that you want the difference between the first time stamp and all subsequent timestamps:

    c_time <- as.POSIXlt( mydf$c_time )
    difftime( c_time[1] , c_time[2:length(c_time)] )
      #Time differences in secs
      #[1]  -59.886 -120.373
      #attr(,"tzone")
      #[1] ""
    

    Edit

    But in case you want the delta difference between subsequent timestamps you need to reverse your obsevations (because the first way round you get time1 - time2 which will be negative), so you can just use instead:

    c_time <- rev( c_time )
    difftime(c_time[1:(length(c_time)-1)] , c_time[2:length(c_time)])
      #Time differences in secs
      #[1] 60.487 59.886
      #attr(,"tzone")
      #[1] ""
    

提交回复
热议问题