title: How to balance a dataset in `dplyr` using `sample_n` automatically to the size of the smallest class?
body: <p>I have a dataset like:</p>
  <pre><code>df &lt;- tibble(
    id = 1:18,
    class = rep(c(rep(1,3),rep(2,2),3),3),
    var_a = rep(c(&quot;a&quot;,&quot;b&quot;),9)
  )
  
  # A tibble: 18 x 3
        id cluster var_a
     &lt;int&gt;   &lt;dbl&gt; &lt;chr&gt;
   1     1       1 a    
   2     2       1 b    
   3     3       1 a    
   4     4       2 b    
   5     5       2 a    
   6     6       3 b    
   7     7       1 a    
   8     8       1 b    
   9     9       1 a    
  10    10       2 b    
  11    11       2 a    
  12    12       3 b    
  13    13       1 a    
  14    14       1 b    
  15    15       1 a    
  16    16       2 b    
  17    17       2 a    
  18    18       3 b 
  </code></pre>
  <p>That dataset contains a number of observations in several classes. The classes are not balanced. In the sample above we can see, that only 3 observations are of class 3, while there are 6 observations of class 2 and 9 observations of class 1.</p>
  <p>Now I want to automatically balance that dataset so that all classes are of the same size. So I want a dataset of 9 rows, 3 rows in each class. I can use the <code>sample_n</code> function from <code>dplyr</code> to do such a sampling.</p>
  <p>I achieved to do so by first calculating the smallest class size..</p>
  <pre><code>min_length &lt;- as.numeric(df %&gt;% 
    group_by(class) %&gt;% 
    summarise(n = n()) %&gt;% 
    ungroup() %&gt;% 
    summarise(min = min(n)))
  </code></pre>
  <p>..and then apply the <code>sample_n</code> function:</p>
  <pre><code>set.seed(1)
  df %&gt;% group_by(cluster) %&gt;% sample_n(min_length)
  
  # A tibble: 9 x 3
  # Groups:   cluster [3]
       id cluster var_a
    &lt;int&gt;   &lt;dbl&gt; &lt;chr&gt;
  1    15       1 a    
  2     7       1 a    
  3    13       1 a    
  4     4       2 b    
  5     5       2 a    
  6    17       2 a    
  7    18       3 b    
  8     6       3 b    
  9    12       3 b    
  </code></pre>
  <p>I wondered If it's possible to do that (calculating the smallest class size and then sampling) in one go?</p>