title: how to stop a loop before last iteration is run in R
body: <p>I am attempting to apply a threshold to a data set of RFID tag reads.  I want to keep all the reads that have a time difference between them greater than the specified threshold.  I have written a piece of code that will do this, but since it is comparing two rows of data, when it gets to the last iteration, it produces an error.  This is a problem, bc I want this loop embedded in another loop and the error breaks the entire process.  Here is what my data looks like.  This is only a small portion, but it represents the larger data set.    </p>
  
  <pre><code>data.rfid.split
                    date        Tag
  1  0013-05-21 16:37:14 04179381FE
  2  0013-05-21 16:39:54 04179381FE
  3  0013-05-21 16:39:56 04179381FE
  4  0013-05-21 16:39:58 04179381FE
  5  0013-05-21 16:40:00 04179381FE
  6  0013-05-21 16:40:02 04179381FE
  7  0013-05-21 16:40:04 04179381FE
  8  0013-05-21 16:40:06 04179381FE
  9  0013-05-21 16:40:08 04179381FE
  10 0013-05-21 16:40:10 04179381FE
  11 0013-05-21 16:40:12 04179381FE
  12 0013-05-21 16:40:14 04179381FE
  13 0013-05-21 16:40:16 04179381FE
  14 0013-05-21 16:40:18 04179381FE
  15 0013-05-21 16:40:20 04179381FE
  16 0013-05-21 16:40:22 04179381FE
  17 0013-05-21 16:40:24 04179381FE
  18 0013-05-21 16:40:26 04179381FE
  19 0013-05-21 16:40:28 04179381FE
  20 0013-05-21 16:40:30 04179381FE
  21 0013-05-21 16:40:32 04179381FE
  22 0013-05-21 16:40:34 04179381FE
  23 0013-05-21 16:41:26 04179381FE
  24 0013-05-21 16:41:31 04179381FE
  
  #this is the threshold I want to use as to filter out unwanted reads.
  thresh &lt;- 33
  </code></pre>
  
  <p>and here is my loop to apply the threshold:</p>
  
  <pre><code>for(k in 2:length(data.rfid.split[,1])){
  repeat{
    diff &lt;- difftime(data.rfid.split[k,1], data.rfid.split[k-1,1], units = "secs")
    if(diff&lt;thresh) data.rfid.split&lt;-data.rfid.split[-(k), ]      
    if(diff&gt;=thresh) break
  
    }
  }
  </code></pre>
  
  <p>as I said, it gives me the desired outcome:</p>
  
  <pre><code>                  date        Tag
  1  0013-05-21 16:37:14 04179381FE
  2  0013-05-21 16:39:54 04179381FE
  19 0013-05-21 16:40:28 04179381FE
  23 0013-05-21 16:41:26 04179381FE
  </code></pre>
  
  <p>but it also gives an error:<br>
    missing value where TRUE/FALSE needed</p>
  
  <p>how can I use this loop an another similar one to get the desired outcome without an error so that this loop can be embedded in another loop?</p>