title: Using quantile function in data.table
body: <p>I try to calculate the mean of some values in a data.table. The mean should be calculated without outliers, which means i have to filter the data first.
  In order to define outliers in my data i use the "default boxplot" approach.</p>
  
  <p>This approach works perfectly:</p>
  
  <pre><code>test &lt;- template[Month==1] # create small subset with data from January
  qnt &lt;- quantile(test$x,c(.25,.75)
  H &lt;- 1.5 * IQR(test$x)
  test[x &lt; (qnt[2]+H) &amp; x &gt; (qnt[1]-H),mean(add)]
  [1] -6113.136
  </code></pre>
  
  <p>I can also make the calculations within the datatable:</p>
  
  <pre><code>test &lt;- template[Month==1] # create small subset with data from January
  test[x &lt; (quantile(x,0.75)+1.5*IQR(x)) &amp; x &gt; (quantile(x,0.25)-1.5*IQR(x)),mean(x)]
  [1] -6113.136
  </code></pre>
  
  <p>Since i need the mean not only for January but for all months i tried this:</p>
  
  <pre><code>template[x &lt; (quantile(x,0.75)+1.5*IQR(x)) &amp; x &gt; (quantile(x,0.25)-1.5*IQR(x)),mean(x),by=Month]
   1:     1 -5601.3050 &lt;&lt;&lt; not the same value than before
   2:     2  1187.3186
   ...
  </code></pre>
  
  <p>The January of the last approach is different than the January before. As far as i could figure out the quantile() method is the issue. I guess it doesn't include the 'by=Month' grouping of the data.table.</p>
  
  <p>Is there anything wrong about my general approach?
  Is there a way to make those calculations without splitting the 'template' data.table in 12 smaller tables first?</p>
  
  <p>Many thanks for your help!</p>
  
  <p><strong>Update:</strong></p>
  
  <pre><code>template[,.SD[x &lt; (quantile(x,0.75)+1.5*IQR(x)) &amp; x &gt; (quantile(x,0.25)-1.5*IQR(x)),mean(x)],by=Month]
  1:     1 -6113.1362
  2:     2  1529.4808
  </code></pre>
  
  <p>Thanks @Frank and @Roland for the super fast support!</p>