title: Group sum on 2 variables and subtraction from total
body: <p>I have a <code>data.table</code> of the following form:-</p>
  <pre><code>library(data.table)
  b &lt;- data.table(Code_Nm = c(rep(&quot;a&quot;, 3), rep(&quot;b&quot;, 3), rep(&quot;d&quot;, 3)),
              Year = rep(2011:2013, 3), total = rep(10, 9),
              a = c(rep(0, 3), 1:6), b = c(7:9, 0, 0, 0, 10:12), d = c(13:18, 0, 0, 0))
  b
  
  #   Code_Nm Year total a  b  d
  #1:       a 2011    10 0  7 13
  #2:       a 2012    10 0  8 14
  #3:       a 2013    10 0  9 15
  #4:       b 2011    10 1  0 16
  #5:       b 2012    10 2  0 17
  #6:       b 2013    10 3  0 18
  #7:       d 2011    10 4 10  0
  #8:       d 2012    10 5 11  0
  #9:       d 2013    10 6 12  0
  </code></pre>
  <p>I want to get a <code>data.table</code> such that the last column named <code>actual</code> has the value equal to the <code>total</code> minus the sum of yearly groups of each <code>Code_Nm</code>. I.e. for <code>a</code> in <code>2011</code> it is <code>10</code> minus sum of all the <code>2011</code> values but from column <code>a</code>. This is equal to <code>10 - (1+4)</code>.</p>
  <p>Similarly for <code>a</code> in <code>2012</code>, it is <code>10</code> minus sum of all <code>2012</code> values but from column <code>a</code>. This is equal to <code>10 - (2+5)</code>.</p>
  <p>Similary for <code>b</code> in <code>2011</code> it is <code>10</code> minus sum of all the <code>2011</code> values but from column <code>b</code>. This is equal to <code>10 - (7+10)</code>. For <code>b</code> in <code>2012</code>, it is <code>10</code> minus sum of all <code>2012</code> values but from column <code>b</code>. This is equal to <code>10 - (8+11)</code>.</p>
  <p>And similary for <code>d</code> column as well.</p>
  <p>The final result is the following <code>data.table</code>:-</p>
  <pre><code>b &lt;- data.table(Code_Nm = c(rep(&quot;a&quot;, 3), rep(&quot;b&quot;, 3), rep(&quot;d&quot;, 3)),
              Year = rep(2011:2013, 3), total = rep(10, 9),
              a = c(rep(0, 3), 1:6), b = c(7:9, 0, 0, 0, 10:12), d = c(13:18, 0, 0, 0),
              actual = c(5, 3, 1, -7, -9, -11, -19, -21, -23))
  b
  
  #   Code_Nm Year total a  b  d actual
  #1:       a 2011    10 0  7 13      5
  #2:       a 2012    10 0  8 14      3
  #3:       a 2013    10 0  9 15      1
  #4:       b 2011    10 1  0 16     -7
  #5:       b 2012    10 2  0 17     -9
  #6:       b 2013    10 3  0 18    -11
  #7:       d 2011    10 4 10  0    -19
  #8:       d 2012    10 5 11  0    -21
  #9:       d 2013    10 6 12  0    -23
  </code></pre>
  <p>Please give a solution using a <code>data.table</code>.</p>
  <p>Thanks in advance.</p>