title: Optimization of calculating time to a future event
body: <p>I have two data frames, one with experimental data for 57 subjects in 2 blocks of 250 trials each (28500 rows total) and one that has the subject, row, block and trial number of all trials where a drift correction was performed (160 rows total). Here is what the relevant columns look like in the two files:</p>
  
  <p>Experimental data:</p>
  
  <pre><code>&gt; head(dori.np[c("userid","blocknum","trialnum")])
     userid blocknum trialnum
  26      1        1        1
  27      1        1        2
  28      1        1        3
  29      1        1        4
  30      1        1        5
  31      1        1        6
  </code></pre>
  
  <p>Drift correction data:</p>
  
  <pre><code>&gt; head(driftCor.user)
    userid driftTrials blocknum trialnum
  1      4          61        1       61
  2      4         140        1      140
  3      5           1        1        1
  4      6         208        1      208
  5      8          71        1       71
  6      8         197        1      197
  </code></pre>
  
  <p>What I want to do is calculate for every trial for each participant how far (in trials) the nearest drift correction is in the future. Right now I am doing it with nested loops, but it takes a very long time for it to run.</p>
  
  <pre><code>numTilDrifCor&lt;-numeric(0)
  for (i in driftCor.user$userid) {
    temp1 &lt;- subset(driftCor.user,driftCor.user$userid==i)
  
    for (j in temp1$blocknum) {
      temp2&lt;-subset(dori.np,dori.np$userid==i &amp; dori.np$blocknum==j)
      driftTrials&lt;-subset(temp1,temp1$blocknum==j)
  
      n &lt;- 1
      for (k in 1:250) {
        if (n &lt;= length(driftTrials$trialnum)) {
          diff &lt;- driftTrials$trialnum[n] - k
  
          if (diff &gt; 0) {
            numTilDrifCor &lt;- c(numTilDrifCor,diff)
          } else if (diff == 0) {
            numTilDrifCor &lt;- c(numTilDrifCor,0)
            n &lt;- n + 1
          }
  
        } else {
          numTilDrifCor &lt;- c(numTilDrifCor,NA)
        }
      }
    }
  }
  </code></pre>
  
  <p>Is there a faster way to do this?</p>