title: R Function looping over new row using previous row data
body: <p>I am trying to categorize incoming temperature data for early detection of an increasing trend (event =1) or a decreasing trend (event =2). The start of an uptrend is characterized by a 1% increase from the lowest point (Pl). The start of a downtrend is characterized by a 1% decrease from the highest point (Ph)</p>
  
  <p>Dataset is initialized with trend=1, Ph and Pl = Temperature and I would like to loop over each new row, updating Pl/Ph and categorize the event type.</p>
  
  <p><strong>Dataset used</strong></p>
  
  <pre><code>data &lt;- data.frame (Temperature=c(93.37, 93.44, 93.22, 93.28, 93.32, 93.48, 93.32, 92.49, 92.21, 92.16, 91.31, 91.30, 91.37, 91.30, 91.21, 91.37, 91.59, 91.45, 92.07, 92.16, 92.35, 92.52, 92.48, 92.13, 92.46), 
                      event=c(1, rep(NA, 24)), Ph=c(93.37, rep(NA, 24)), Pl=c(93.37, rep(NA, 24)))
  </code></pre>
  
  <p><strong>Expected result</strong></p>
  
  <pre><code>data &lt;- data.frame (Temperature=c(93.37, 93.44, 93.22, 93.28, 93.32, 93.48, 93.32, 92.49, 92.21, 92.16, 91.31, 91.30, 91.37, 91.30, 91.21, 91.37, 91.59, 91.45, 92.07, 92.16, 92.35, 92.52, 92.48, 92.13, 92.46), 
  event=c(1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1), 
  Ph=c(93.37,NA,NA,NA,NA,NA,NA,92.49,92.21,92.16,91.31,91.3,91.3,91.3,91.21,91.21,91.21,91.21,91.21,NA,NA,NA,NA,NA,NA),
  Pl=c(93.37,93.44,93.44,93.44,93.44,93.48,93.48,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,92.16,92.35,92.52,92.52,92.52,92.52))
  </code></pre>
  
  <p>I fail to convert the following code into a loop that can perform these commands on an historical dataset. I have tried a function as well as the apply family without success.</p>
  
  <pre><code>data$Ph_lag &lt;- lag(data$Ph, 1)
  data$Pl_lag &lt;- lag(data$Pl, 1)
  
  for(i in 2:nrow(data)) {
  
    if (data$event[i-1] == 1) {
  
      if (data$Temperature[i]  &lt;= data$Ph_lag[i] * 0.99) { # missing value where TRUE/FALSE needed (=all NA ROWS)
        data$event[i]  &lt;- 2
        data$Pl[i] &lt;- data$Close[i]
  
      } else if (data$Temperature[i] &gt; data$Ph_lag[i]) { 
        data$Ph[i] &lt;- data$Temperature[i]
        data$event[i] &lt;- 1
  
      } else {  
        data$Ph[i] &lt;- data$Ph_lag[i]
        data$event[i] &lt;- 1
      }  
  
    } else if (data$event[i-1] == 2) { 
  
      if (data$Temperature[i]  &gt;= data$Pl_lag[i]  * 1.01) { 
        data$event[i]  &lt;- 1
        data$Ph[i] &lt;- data$Temperature[i]
  
      } else if (data$Temperature[i] &lt; data$Pl_lag[i]) { 
        data$Pl[i] &lt;- data$Temperature[i]
        data$event[i]  &lt;- 2
  
      } else {  
        data$Pl[i] &lt;- data$Pl_lag[i]
        data$event[i]  &lt;- 2
      }}}
  </code></pre>
  
  <p>In its current state, this code is successful when applied to a single row, but can hardly be used to fill up historical data containing thousands of observations.</p>
  
  <p>Comments appreciated, would be very grateful</p>