title: Keeping factor order after gather and summarise steps in tidyverse
body: <p>I have over a hundred variables for which I'm trying to calculate frequency and percent. How can I maintain the factor order of each variables' values in the output? Please note that specifying the order for each variable outside the dataset is not practical as I have over 100 variables.</p>
  <p>Example data:</p>
  <pre><code>df &lt;- data.frame(gender=factor(c(&quot;male&quot;, &quot;female&quot;, &quot;male&quot;, NA), levels=c(&quot;male&quot;, &quot;female&quot;)),
                   disease=factor(c(&quot;yes&quot;,&quot;yes&quot;,&quot;no&quot;, NA), levels=c(&quot;yes&quot;, &quot;no&quot;)))
  df
    gender disease
  1   male     yes
  2 female     yes
  3   male      no
  4   &lt;NA&gt;    &lt;NA&gt;
  </code></pre>
  <p>Attempt:</p>
  <pre><code>df %&gt;% gather(key, value, factor_key = T) %&gt;%
    group_by(key, value) %&gt;% 
    summarise(n=n()) %&gt;%
    ungroup() %&gt;%
    group_by(key) %&gt;%
    mutate(percent=n/sum(n))
  </code></pre>
  <p>Output:</p>
  <pre><code># A tibble: 6 x 4
  # Groups:   key [2]
    key     value      n percent
    &lt;fct&gt;   &lt;chr&gt;  &lt;int&gt;   &lt;dbl&gt;
  1 gender  female     1    0.25
  2 gender  male       2    0.5 
  3 gender  NA         1    0.25
  4 disease no         1    0.25
  5 disease yes        2    0.5 
  6 disease NA         1    0.25
  </code></pre>
  <p>Desired output would order gender as male, female and disease as yes, no.</p>