title: Aggregating sub totals and grand totals with data.table
body: <p>I've got a <code>data.table</code> in R:</p>
  
  <pre><code>library(data.table)
  set.seed(1)
  DT = data.table(
    group=sample(letters[1:2],100,replace=TRUE), 
    year=sample(2010:2012,100,replace=TRUE),
    v=runif(100))
  </code></pre>
  
  <p>Aggregating this data into a summary table by group and year is simple and elegant:</p>
  
  <pre><code>table &lt;- DT[,mean(v),by='group, year']
  </code></pre>
  
  <p>However, aggregating this data into a summary table, including subtotals and grand totals, is a little more difficult, and a lot less elegant:</p>
  
  <pre><code>library(plyr)
  yearTot &lt;- DT[,list(mean(v),year='Total'),by='group']
  groupTot &lt;- DT[,list(mean(v),group='Total'),by='year']
  Tot &lt;- DT[,list(mean(v), year='Total', group='Total')]
  table &lt;- rbind.fill(table,yearTot,groupTot,Tot)
  table$group[table$group==1] &lt;- 'Total'
  table$year[table$year==1] &lt;- 'Total'
  </code></pre>
  
  <p>This yields:</p>
  
  <pre><code>table[order(table$group, table$year), ]
  </code></pre>
  
  <p>Is there a simple way to specify subtotals and grand totals with data.table, such as the <code>margins=TRUE</code> command for plyr?  I would prefer to use data.table over plyr on my dataset, as it is a very large dataset that I already have in the data.table format.</p>