title: R data.table Conditional Sum: Cleaner way
body: <p><em>This of course is a very often encountered problem, so I have expected many questions here on SO regarding this. However, all the answers that I could find were very specific to the question and often encountered workarounds (you don't have to do this, <strong>foobar</strong> is much better in this scenario) or non data.table solutions. Perhaps this is because it should be a no-brainer with data.table</em></p>
  
  <p>I have a data.table which contains yearly data on <code>tentgelt</code> and <code>te_med</code>. For each year, I want to know the share of observations for which <code>tentgelt &gt; te_med</code>. This is what I am doing:</p>
  
  <pre><code># note that nAbove and nBelow do not add up to 1
  nAbove &lt;- wages[tentgelt &gt; te_med, list(nAbove = .N), by=list(year)]
  nBelow &lt;- wages[tentgelt &lt; te_med, list(nBelow = .N), by=list(year)]
  nBelow[nAbove][, list(year, foo=nAbove/(nAbove+nBelow))]
  </code></pre>
  
  <p>which works but whenever I see other people's <code>data.table</code> code, it looks much clearer and easier than my workarounds. Is there a cleaner way to get the following type of output?</p>
  
  <pre><code>   year       foo
   1: 1993 0.2372093
   2: 1994 0.1567568
   3: 1995 0.8132530
   4: 1996 0.1235955
   5: 1997 0.1065574
   6: 1998 0.3070684
   7: 1999 0.1491974
  </code></pre>
  
  <p>Here's a sample of my data:</p>
  
  <pre><code>   year tentgelt    te_med
   1: 2010   120.95  53.64929
   2: 2010     9.99 116.72601
   3: 2010   113.52  53.07394
   4: 2010    10.27  38.45728
   5: 2010    48.58 124.65753
   6: 2010    96.38  86.99060
   7: 2010     3.46  65.75342
   8: 2010   107.52  91.87592
   9: 2010   107.52  42.92953
  10: 2010     3.46  73.92328
  11: 2010    96.38  85.23419
  12: 2010     2.25  79.19995
  13: 2010    42.32  35.75757
  14: 2010     7.94  93.44305
  15: 2010   120.95 113.41370
  16: 2010     7.94 110.68628
  17: 2010   107.52 127.30682
  18: 2010     2.25 103.49036
  19: 2010   120.95 123.62054
  20: 2010    96.38  68.57532
  </code></pre>
  
  <p>For this sample, the <strong>expected output</strong> should be:</p>
  
  <pre><code>   year   V2
  1: 2010 0.45
  </code></pre>