title: How to find and label start / end points of unique sequences in R
body: <p>I have a sequence of 1s and 0s alongside a time vector. I'd like to find the start and end time points of all the sequences of 1s, and give each sequence a unique ID. Here is some example data and my attempt so far.</p>
  
  <h1>Create dummy data</h1>
  
  <pre><code># Create the sequence
  x = c(0,0,0,0,1,1,1,1,0,0,0,1,1,1,1,1,1,0,0,0,1,1,1,1,0)
  
  # Create the time vector
  t = 10:34
  </code></pre>
  
  <h1>This is my effort</h1>
  
  <pre><code>#Get changepoints using diff()
  diff_result &lt;- diff(x)
  
  # Use ifelse() to get start and end times (i.e. on and off)
  on_t &lt;- ifelse(diff_result == 1, t, NA)
  off_t &lt;- ifelse(diff_result == -1, t, NA)
  
  # Combine into data frame and remove NAs, add 1 to on_t
  results &lt;- data.frame(on_t  = on_t[!is.na(on_t)] + 1, off_t = off_t[!is.na(off_t)])
  
  # Create unique ID for each sequence
  results$ID &lt;- factor(1:nrow(results))
  
  print(results)
  
    on_t off_t ID
  1   14    17  1
  2   21    26  2
  3   30    33  3
  </code></pre>
  
  <p>I'm sure there's a better way...</p>