title: R Identifying pairs in irregular dataset
body: <p>I need to identify pairs of arrivals and departures. The <code>movement</code> variable identifies <code>ARR</code> and <code>DEP</code> but sometimes among <code>ARR</code>-<code>DEP</code> pairs there are other rows that mess things up. I would like to keep <code>ARR</code>-<code>DEP</code> pairs and discard the rest. </p>
  
  <p>Data looks mostly like this: </p>
  
  <pre><code>  id    time            movement    origin  dest
     1    10/06/2011 15:54    ARR        15    15
     1    10/06/2011 16:14    DEP        15    29
     2    10/06/2011 17:59    ARR        73    73
     2    10/06/2011 18:10    DEP        73    75
     2    10/06/2011 21:10    ARR        75    75
     2    10/06/2011 21:20    DEP        75    73
  </code></pre>
  
  <p>If you load the data below, you will see "misbehaved" cases at <code>id</code> Id5: Standalone movement without pair to match. Id 6: Extra <code>DEP</code> record (that I would discard) and Id 8: <code>DEP</code> first instead of <code>ARR</code>. </p>
  
  <p>I have tried the following: </p>
  
  <pre><code>dfru$test &lt;- FALSE
  dfru$test[which(dfru$movement == "ARR")] &lt;- TRUE
  </code></pre>
  
  <p><code>dfru$test[which(dfru$test[-1] =="TRUE")] &lt;- 1</code> #Doesn't work (i.e. assigns TRUE or 1 to <code>id</code> 5 and not to the last record of <code>id</code>4. </p>
  
  <p>If I change the last line for <code>dfru$test[which(dfru$test[-1] =="TRUE" &amp; dfru$movement == "DEP")] &lt;- 1</code> it doesn't work either to match trips. </p>
  
  <p>Any ideas? Commands/packages that I could use? </p>
  
  <p>Data: </p>
  
  <pre><code>dfru &lt;- structure(list(time = structure(c(7L, 16L, 8L, 11L, 18L, 20L, 
  10L, 12L, 3L, 6L, 15L, 19L, 9L, 4L, 5L, 14L, 1L, 2L, 13L, 17L
  ), .Label = c("10/06/2011 09:08", "10/06/2011 10:54", "10/06/2011 11:38", 
  "10/06/2011 12:41", "10/06/2011 12:54", "10/06/2011 14:26", "10/06/2011 14:33", 
  "10/06/2011 14:59", "10/06/2011 17:12", "10/06/2011 17:14", "10/06/2011 17:23", 
  "10/06/2011 18:56", "10/06/2011 19:03", "10/06/2011 19:04", "10/06/2011 19:16", 
  "10/06/2011 19:24", "10/06/2011 20:12", "10/06/2011 21:10", "10/06/2011 22:28", 
  "10/06/2011 23:40"), class = "factor"), movement = structure(c(1L, 
  2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 3L, 1L, 2L, 2L, 1L, 
  2L, 2L, 3L), .Label = c("ARR", "DEP", "ITZ"), class = "factor"), 
      origin = c(15L, 15L, 73L, 73L, 75L, 75L, 17L, 17L, 49L, 49L, 
      15L, 15L, 32L, 10L, 10L, 17L, 76L, 76L, 76L, 76L), dest = c(15L, 
      29L, 73L, 75L, 75L, 73L, 17L, 48L, 49L, 15L, 15L, 49L, 32L, 
      10L, 17L, 10L, 76L, 65L, 76L, 65L), id = c(1L, 1L, 2L, 2L, 
      2L, 2L, 3L, 3L, 4L, 4L, 4L, 4L, 5L, 6L, 6L, 6L, 7L, 7L, 8L, 
      8L)), .Names = c("time", "movement", "origin", "dest", "id"
  ), row.names = c(NA, -20L), class = c("data.table", "data.frame"
  ))
  </code></pre>