title: Replace a sequence of values by group depending on preceeding values
body: <p>I have a data table of this form (2000000+ rows, 1000+groups):</p>
  
  <pre><code>set.seed(1)    
  dt &lt;- data.table(id = rep(1:3, each = 5), values = sample(c("a", "b","c"), 15, TRUE))
  
  &gt; dt
      id values
   1:  1      a
   2:  1      c
   3:  1      a
   4:  1      b
   5:  1      a
   6:  2      c
   7:  2      c
   8:  2      b
   9:  2      b
  10:  2      c
  11:  3      c
  12:  3      a
  13:  3      a
  14:  3      a
  15:  3      b
  </code></pre>
  
  <p>I want to, within each ID group, replace the entire sequence of character "a", that precedes the character "b", and I want to replace them with "b". So the condition is that <strong>if "a" or a sequence of "a"s appear before "b"</strong>, <strong>replace all the "a"s</strong>. (actually, in my real table, it's when "b" is preceded by "a","x", or"y", preceding character should be replaced, but I should be able to generalize)</p>
  
  <p>In the example above,the value of "a" in row 3 should be replaced (easy to do with (shift) in data.table), as well as all the "a"s in rows 12-14 (not sure how to do). So, the desired output is this:</p>
  
  <pre><code>&gt; dt
      id values
   1:  1      a
   2:  1      c
   3:  1      b
   4:  1      b
   5:  1      a
   6:  2      c
   7:  2      c
   8:  2      b
   9:  2      b
  10:  2      c
  11:  3      c
  12:  3      b
  13:  3      b
  14:  3      b
  15:  3      b
  </code></pre>
  
  <p>What comes to my mind is looping from the last index, but I am not exactly sure how to do that with if I have multiple groupings (say, ID and DATE), and anyway, this doesn't seem to be the fastest dt solution.</p>