title: Vectorizing for loop: access previous rows of data.frame
body: <p>I am trying to convert a loop to vectorization.  In my application, I have over 2 million rows and looping is too slow.  I have read this post which is very helpful: <a href="https://stackoverflow.com/questions/2908822/speed-up-the-loop-operation-in-r">Speed up the loop operation in R</a></p>
  
  <p>Here is an example of what my data looks like:</p>
  
  <pre><code>m &lt;- data.frame(time = 1:10, level = c(0,0,60,100,0,0,100,100,0,0))
  
  &gt;m
      time level
  1     1     0
  2     2     0
  3     3    60
  4     4   100
  5     5     0
  6     6     0
  7     7   100
  8     8   100
  9     9     0
  10   10     0
  </code></pre>
  
  <p>What I want is a column <code>machine</code> that is either "on" or "off" depending on level.  </p>
  
  <p>if level != 0 then machine = "on"</p>
  
  <p>if level goes to 0, then <code>machine</code> will turn off, after an arbitrary period <code>lag</code>. In this example, say <code>lag = 2</code> then the result would be:</p>
  
  <pre><code>    time level machine
  1     1     0     off
  2     2     0     off
  3     3    60      on
  4     4   100      on
  5     5     0      on
  6     6     0     off
  7     7   100      on
  8     8   100      on
  9     9     0      on
  10    10    0     off
  </code></pre>
  
  <p>Any suggestions how how to vectorize this operation?  I've looked into using <code>lag</code> from dplyr but haven't found a way to make it work.</p>
  
  <p>I've written a loop that works for this example, as an illustration.</p>
  
  <pre><code>m$machine &lt;- ifelse(m$level!=0, "on", 0)
  
  tlag &lt;- 2
  # check to see if timeout period has elapsed
  for (i in seq_along(m$machine)){
      if(m$machine[i]!="on") {
          nback &lt;- i - tout
          if (nback &lt;=0 ) nback &lt;- 1
          if (sum(m$level[nback:i]) == 0){ #light should be off
              m$machine[i] &lt;- "off"
          }
      }
  }
  
  for (i in seq_along(m$machine)){
      if(m$machine[i]==0) m$machine[i] &lt;- "on"   
  }
  </code></pre>