Search code examples
rtimeline

Transform timestamp data into starttimes and endtimes


I'd like to make a timeline in R using either the timevis, timeline, or another package, but I need to transform the data into start and end times to be able to use it. Currently I have a dichotomous variable indicating activity and times like below.

Name    Time    Active
Joe     0       1
Joe     2       1
Joe     4       0
Joe     6       0
Joe     8       1
Joe     10      1
Beth    0       0
Beth    2       1
Beth    4       1
Beth    6       1
Beth    8       0
Beth    10      1

So I'd like to be able to turn this into start and end times, e.g.

Name StartTime EndTime
Joe  0         4

etc.

Does anyone have any ideas of a nice way to do this?


Solution

  • Does this get you started?

      idxRun <- function(df, ...) {
          x <- df$Active
          times <- df$Time
    
          # take a vector x and return a vector of change indicies.
          dif <- diff(x) != 0
          idx <- c(TRUE, dif) 
          dat <- list(
            state=x[idx],
            time=times[idx]
          )
          # now neatly arrange the start / stop times.
          starts <- dat$time[dat$state == 1]
          stops <- dat$time[dat$state == 0 & (dat$time > starts[1])]
          # line up the vectors
          min.len <- min(c(length(starts), length(stops)))
          if(min.len == 0) {
            return(data.frame(start.time = NULL, stop.time = NULL))
          } else {
             return(
               data.frame(
                 start.time = starts[1:min.len],
                 stop.time = stops[1:min.len])
            )
        }
    
      }
    

    Use that with by:

    by(dd,INDICES = dd$Name, FUN=idxRun)
    

    Which gives:

    dd$Name: Beth
      start.time stop.time
    1          2         8
    ------------------------------------------------------------------------------------------- 
    dd$Name: Joe
      start.time stop.time
    1          0         4