title: I need a loop to delete rows according to timestamp difference in R
body: <p>I am working on a project where I have few million rows and each contains timestamp. Each row also includes the unique ID of that event. Current condition is that rows with the same event ID can have timestamp difference of 1 minute (there cant be two events with delta timestamp less than 1minute). </p>
  
  <p>What I want to simulate is the situation which would happen if minimal timestamp difference would be 3 minutes. </p>
  
  <pre><code>    TIME_STAMP              PREV_TIME_STAMP      Unique ID 
  06-27-2021 07:07:22       06-27-2021 06:30:00         1 
  06-27-2021 07:18:26       06-27-2021 07:07:22         1 
  06-27-2021 07:20:26       06-27-2021 07:18:26         1 
  06-27-2021 07:22:26       06-27-2021 07:20:26         1 
  06-27-2021 07:22:26       06-27-2021 07:22:26         1 
  06-27-2021 15:18:05       06-27-2021 15:11:00         2 
  06-27-2021 15:19:05       06-27-2021 15:18:05         2 
  06-27-2021 12:31:37       06-27-2021 12:30:00         2 
  06-27-2021 12:35:05       06-27-2021 12:30:00         2
  </code></pre>
  
  <p>The problem is that I cant only make new column with difference between messages, I do need a loop for this - why? see below:</p>
  
  <p>From the table the situation is following:</p>
  
  <ul>
  <li>First row is accepted as the delta is 37 minutes </li>
  <li>Second row is    accepted as the delta is 11 minutes</li>
  <li>Third row <strong>IS NOT ACCEPTED</strong> as    the delta is 1.5 minutes</li>
  <li>Fourth row <strong>IS ACCEPTED</strong> as the previous    event is <strong>NOT</strong>
  07:20:26, it is 07:18:26 (row three is deleted so it is not considered!). So delta time for 4th row is 07:22:26 - 07:18:26 = 4 minutes > 3 minutes which means accepted</li>
  </ul>
  
  <p>So there is need to define a referent timestamp (it is the previous ACCEPTED time), and delta between new time and previous time WHICH IS ACCEPTED has to be 3 minutes or higher. </p>
  
  <p>I hope that I managed to explain it well enough. If not, please answer and I will provide as much as information I can.</p>
  
  <p>Thanks in advance!</p>
  
  <p>EDIT:</p>
  
  <pre><code>df &lt;- data.frame(TIME_STAMP = as.POSIXct(strptime(
    c("06-27-2021 07:07:22", 
      "06-27-2021 07:18:26",
      "06-27-2021 07:20:26",
      "06-27-2021 07:22:26",
      "06-27-2021 07:22:26",
      "06-27-2021 15:18:05",
      "06-27-2021 15:19:05",
      "06-27-2021 12:31:37",
      "06-27-2021 12:35:05"), "%m-%d-%Y %H:%M:%S")),
    PREV_TIME_STAMP = as.POSIXct(strptime(
      c("06-27-2021 06:30:00",
        "06-27-2021 07:07:22",
        "06-27-2021 07:18:26",
        "06-27-2021 07:20:26",
        "06-27-2021 07:22:26",
        "06-27-2021 15:11:00",
        "06-27-2021 15:18:05",
        "06-27-2021 12:30:00",
        "06-27-2021 12:30:00"), "%m-%d-%Y %H:%M:%S")),
    ID = c(1,1,1,1,1,2,2,2,2))
  </code></pre>