title: Assigning values in a sequence depending on previous row in R
body: <p>I have a data table like this.</p>
  
  <pre><code>  ID1 ID2 member
  1   a   x parent
  2   a   y  child
  3   a   z parent
  4   a   p  child
  5   a   q  child
  6   b   x parent
  7   b   z parent
  8   b   q  child
  </code></pre>
  
  <p>And I want to assign a sequence like below.</p>
  
  <pre><code>  ID1 ID2 member sequence
  1   a   x parent        1
  2   a   y  child        2
  3   a   z parent        1
  4   a   p  child        2
  5   a   q  child        3
  6   b   x parent        1
  7   b   z parent        1
  8   b   q  child        2
  </code></pre>
  
  <p>i.e.</p>
  
  <pre><code>&gt; dt$sequence = 1, wherever dt$member == "parent"
  
  &gt; dt$sequence = previous_row_value + 1, wherever dt$member=="child"
  </code></pre>
  
  <p>As of now I have been doing it using loops, like below.</p>
  
  <pre><code>dt_sequence &lt;- dt[ ,sequencing(.SD), by="ID1"]
  
  sequencing &lt;- function(dt){
    for(i in 1:nrow(dt)){
      if(i == 1){
        dt$sequence[i] = 1
        next
      }
      if(dt[i,member] %in% "child"){
        dt$sequence[i] = as.numeric(dt$sequence[i-1]) + 1
      }
      else
        dt$sequence[i] = 1
    }
    return(dt)
  }
  </code></pre>
  
  <p>I ran this code on a data table of 400 000 rows and it took a lot of time to complete (around 15 mins).
  Can anyone suggest a faster way to do it.</p>