title: Assigning values to a group based on previous rows in R
body: <p>I have a data table like this:</p>
  
  <pre><code>  ID Type
    1    I
    1    A
    1    A
    2    I
    2    A
    2    I  
    2    C
    2    I
    2    I
  </code></pre>
  
  <p>I want to add a column Sequence like below:</p>
  
  <pre><code>   ID Type Seq
     1    I   1
     1    A   1
     1    A   1
     2    I   1
     2    A   1
     2    I   2
     2    C   2
     2    I   3
     2    I   4
  </code></pre>
  
  <p>The logic is:<br/>
  Seq = previous_row_for_user_where_I_occurs +1, when Type=I <br/>
  Seq = previous occurrence of I for the user, when Type=A or C <br/></p>
  
  <p>So basically, for a given user number all occurrences of I sequentially. If A or C occurs in between, then assign it the value of I that occurs before it. The IDs have been sorted using a date field. <br/></p>
  
  <p>I referred to the below also but it did not help because if "A" occurs twice for a User, the second occurrence is not numbered correctly. <br/>
  <a href="https://stackoverflow.com/questions/27335527/assigning-values-in-a-sequence-depending-on-previous-row-in-r">Assigning values in a sequence depending on previous row in R</a></p>
  
  <p>I am using a for loop now which takes hours as I have 10 million rows.</p>