title: R: Slicing a grouped data frame conditional on a column
body: <p>I have a data frame with a group, a condition that differs by group, and an index within each group:</p>
  <pre><code>df &lt;- data.frame(group = c(rep(c(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;), each = 3)), 
                   condition = rep(c(0,1,1), each = 3), 
                   index = c(1:3,1:3,2:4))
  
  &gt; df
    group condition index
  1     A         0     1
  2     A         0     2
  3     A         0     3
  4     B         1     1
  5     B         1     2
  6     B         1     3
  7     C         1     2
  8     C         1     3
  9     C         1     4
  </code></pre>
  <p>I would like to slice the data within each group, filtering out all but the row with the lowest index. However, this filter should only be applied when the condition applies, i.e., <code>condition == 1</code>. My solution was to compute a ranking on the index within each group and filter on the combination of condition and rank:</p>
  <pre><code>df %&gt;%
    group_by(group) %&gt;%
    mutate(rank = order(index)) %&gt;%
    filter(case_when(condition == 0 ~ TRUE,
                     condition == 1 &amp; rank == 1 ~ TRUE))
  
  # A tibble: 5 x 4
  # Groups:   group [3]
    group condition index  rank
    &lt;chr&gt;     &lt;dbl&gt; &lt;int&gt; &lt;int&gt;
  1 A             0     1     1
  2 A             0     2     2
  3 A             0     3     3
  4 B             1     1     1
  5 C             1     2     1
  </code></pre>
  <p>This left me wondering whether there is a faster solution that does not require a separate ranking variable, and potentially uses slice_min() instead.</p>