title: Conditional difference calculation in data table
body: <p>I have a millions row long <code>data.table</code> with about 20 counter-style columns. Those columns display various storage system operations' counters increasing in time. Sometimes however, the counter gets reset on the monitored system and the single observation value is lower than a previous one.</p>
  
  <p>I need to calculate a <code>opsdiff</code> column, which would contain an arithmetical difference (expected to be positive) of subsequent values of same type based on column <code>type</code>. When a counter reset situation is identified - ie. the difference is negative, the actual value of the counter should be used.</p>
  
  <pre><code>&gt; dt &lt;- data.table(type=rep(c("a","b"),each=6),opscounter=c(105609,106316,106705,489,723,1250))
  &gt; dt
      type opscounter
   1:    a     105609
   2:    a     106316
   3:    a     106705
   4:    a        489
   5:    a        723
   6:    a       1250
   7:    b     105609
   8:    b     106316
   9:    b     106705
  10:    b        489
  11:    b        723
  12:    b       1250
  </code></pre>
  
  <p>The result I wish to get:</p>
  
  <pre><code>&gt; dt
      type opscounter     opsdiff
   1:    a     105609          NA
   2:    a     106316         707
   3:    a     106705         389
   4:    a        489         489
   5:    a        723         234
   6:    a       1250         527
   7:    b     105609          NA
   8:    b     106316         707
   9:    b     106705         389
  10:    b        489         489
  11:    b        723         234
  12:    b       1250         527
  &gt; 
  </code></pre>
  
  <p>I tried to build a construction based on <code>ifelse()</code> but I don't know how to address the current row's <code>opscounter</code> value in <em>else</em> part and neither the dual call of <code>diff()</code> is perhaps an efficient usage:</p>
  
  <pre><code>dt[,opsdiff:=c(NA, ifelse(diff(opscounter)&gt;0, diff(opscounter), opscounter)), by=type]
  </code></pre>
  
  <p>How can I correctly calculate the <code>opsdiff</code> column?</p>