title: Order of groups in R dplyr group_by function
body: <p>I'm using the <code>dplyr::group_by()</code> function in order to summarise some data. Let's assume the following dataframe:</p>
  
  <pre><code>set.seed(1)
  df &lt;- data.frame(ans = sample(c("Yes", "No"), size = 10, replace = TRUE),
                       sex = factor(sample(c("Male", "Female"), size = 10, replace = TRUE)),
                       age = sample(c(10, 20, 30), size = 10, replace = TRUE),
                       res = rnorm(10, mean = 1, sd = 10))
  </code></pre>
  
  <p>The output after the summary is as follows:</p>
  
  <pre><code>df %&gt;% dplyr::group_by(ans, sex, age) %&gt;% summarise(mean_ans = mean(res, na.rm = TRUE))
  
  # A tibble: 9 x 4
  # Groups:   ans, sex [?]
    ans   sex      age mean_ans
    &lt;fct&gt; &lt;fct&gt;  &lt;dbl&gt;    &lt;dbl&gt;
  1 No    Female    10    8.82 
  2 No    Female    20    6.09 
  3 No    Male      10    9.21 
  4 No    Male      20   10.2  
  5 No    Male      30  -18.9  
  6 Yes   Female    10    6.94 
  7 Yes   Female    20    7.20 
  8 Yes   Male      10    0.838
  9 Yes   Male      30    0.551
  </code></pre>
  
  <p>It seems that <code>group_by()</code> lists the groups alphabetically (conflicts resolved by the next grouping variable). What about the <code>age</code> variable - why isn't it in some order (e.g. 10, 20, 30)?</p>
  
  <p>If I use <code>age</code> as the first grouping variable I get a dataframe that is sorted by all three grouping variables:</p>
  
  <pre><code>dplyr::group_by(age, sex, ans) %&gt;% summarise(mean_ans = mean(res, na.rm = TRUE))
  
  # A tibble: 9 x 4
  # Groups:   age, sex [?]
      age sex    ans   mean_ans
    &lt;dbl&gt; &lt;fct&gt;  &lt;fct&gt;    &lt;dbl&gt;
  1    10 Female No       8.82 
  2    10 Female Yes      6.94 
  3    10 Male   No       9.21 
  4    10 Male   Yes      0.838
  5    20 Female No       6.09 
  6    20 Female Yes      7.20 
  7    20 Male   No      10.2  
  8    30 Male   No     -18.9  
  9    30 Male   Yes      0.551
  </code></pre>
  
  <p>Is it always the case that <code>group_by()</code> returns a data frame ordered alphabetically by character and factor variables? According to <a href="https://github.com/tidyverse/dplyr/issues/2159" rel="nofollow noreferrer">this discussion</a> it is the case but since the discussion took place in 2016 I'd like to know whether the conclusions are still valid. </p>
  
  <p><strong>EDIT</strong>: I ran the original data frame with 100 rows so that all 12 groups (2*2*3) are created. It seems obvious that the data frame is sorted (including numerical columns). However, I'm not satisfied with my 'investigation' - is there a general-case proof (my simulation is one out of many). Do you know any counterexamples?</p>