title: data.table, filter >= median per group and keep two lowest
body: <p><strong>Situation &amp; Goal</strong></p>
  <p>I'm having a large table that looks like (simplified):</p>
  <pre><code>|MainCat |SubCat | Value|
  |:-------|:------|-----:|
  |A       |Y      |    50|
  |A       |Z      |    60|
  |A       |ZZZZ   |    80|
  |A       |XX     |    90|
  |A       |X      |   100|
  |B       |XYXY   |    15|
  |B       |XXX    |    50|
  |B       |YY     |    60|
  |B       |ZZZ    |   150|
  |B       |ZZ     |   400|
  </code></pre>
  <p>Now I want to filter each group (<code>MainCat</code>) and keep only the two lowest values (<code>Value</code>) that are equal/greater than median:</p>
  <pre><code>|MainCat |SubCat | Value|Comment               |
  |:-------|:------|-----:|:---------------------|
  |A       |Y      |    50|-                     |
  |A       |Z      |    60|-                     |
  |A       |ZZZZ   |    80|Median, First to keep |
  |A       |XX     |    90|Second to keep        |
  |A       |X      |   100|-                     |
  |B       |XYXY   |    15|-                     |
  |B       |XXX    |    50|-                     |
  |B       |YY     |    60|Median, First to keep |
  |B       |ZZZ    |   150|Second to keep        |
  |B       |ZZ     |   400|-                     |
  </code></pre>
  <hr />
  <p><strong>Expected result:</strong></p>
  <pre><code>|MainCat |SubCat | Value|
  |:-------|:------|-----:|
  |A       |ZZZZ   |    80|
  |A       |XX     |    90|
  |B       |YY     |    60|
  |B       |ZZZ    |   150|
  </code></pre>
  <hr />
  <p><strong>My (failed) attempt</strong></p>
  <p>I tried <code>df2[Value &gt;= df2[MainCat==MainCat, median(Value, na.rm=TRUE)]]</code> but this calculates a Median for all values, without grouping. Can somebody help? As performance is key, I prefer a <code>data.table</code> solution if possible. Thank you very much.</p>
  <hr />
  <p><strong>MWE</strong></p>
  <p>Base data:</p>
  <pre><code>df2 = structure(list(MainCat = c(&quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;B&quot;, &quot;B&quot;, 
                                   &quot;B&quot;, &quot;B&quot;, &quot;B&quot;), SubCat = c(&quot;Y&quot;, &quot;Z&quot;, &quot;ZZZZ&quot;, &quot;XX&quot;, &quot;X&quot;, &quot;XYXY&quot;, 
                                                  &quot;XXX&quot;, &quot;YY&quot;, &quot;ZZZ&quot;, &quot;ZZ&quot;), Value = c(50, 60, 80, 90, 100, 15, 
                                                               50, 60, 150, 400)), row.names = c(NA, -10L), class = c(&quot;data.table&quot;, 
                                                                  &quot;data.frame&quot;))
  </code></pre>
  <p>Result:</p>
  <pre><code>data.table(MainCat=c(&quot;A&quot;,&quot;A&quot;,&quot;B&quot;,&quot;B&quot;),
                   SubCat=c(&quot;ZZZZ&quot;, &quot;XX&quot;, &quot;YY&quot;, &quot;ZZZ&quot;),
                   Value=c(80,90,60,150))
  </code></pre>