title: Create a data column in an R dataframe based on a sequential comparison
body: <p>I am having an issue trying to generate values based off of a sequential conditional comparison from values in another column of a data frame.</p>
  
  <p>Here are example Data:</p>
  
  <pre><code>ID  Tracked
  
  1   Yes
  1   Yes    
  1   No    
  1   No    
  1   Yes    
  1   Yes   
  2   Yes    
  2   No    
  2   No    
  2   Yes    
  2   Yes    
  2   Yes    
  2   No    
  2   Yes
  </code></pre>
  
  <p>What I would like is to add a third column based off of whether ID has at least a previous and successive Yes like this.</p>
  
  <pre><code>ID  Tracked Seq
  
  1   Yes     NA    
  1   Yes     1    
  1   No      0    
  1   No      0    
  1   Yes     0    
  1   Yes     1    
  2   Yes     NA    
  2   No      0    
  2   No      0    
  2   Yes     0    
  2   Yes     1    
  2   Yes     1    
  2   No      0    
  2   Yes     0
  </code></pre>
  
  <p>Many thanks for all your help.  I have tried numerous things and can not seem to come up with simple code but it is looking like I will need to construct a nested for loop.</p>
  
  <p>The latest for loop I have tried (without looping over per ID yet as a test) is not working, just returning all zeros.</p>
  
  <pre><code>for (i in length(Data)){
     Data$Seq[i+1] &lt;- ifelse(Data$Tracked[i]==Data$Tracked[i+1], 1, 0)
  }
  </code></pre>
  
  <p>And the solution that works with the help of @parksw3</p>
  
  <pre><code>for (i in 1:(nrow(df)-1)){
      df$Seq[1] &lt;- NA
      df$Seq[i+1] &lt;- 
      ifelse(df$Tracked[i]==df$Tracked[i+1], 1, 0) *
      ifelse(df$ID[i] == df$ID[i+1], 1, NA)
  }
  </code></pre>