title: R: convert to factor with order of levels same with case_when
body: <p>When doing data analysis, I sometimes need to recode values to factors in order to carry out groups analysis. I want to keep the order of factor same as the order of conversion specified in <code>case_when</code>. In this case, the order should be <code>&quot;Excellent&quot;  &quot;Good&quot;  &quot;Fail&quot;</code>. How can I achieve this without tediously mention it again as in <code>levels=c('Excellent', 'Good', 'Fail')</code>?</p>
  <p>Thank you very much.</p>
  
  <br/>
  <pre class="lang-r prettyprint-override"><code>library(dplyr, warn.conflicts = FALSE)             
                                                     
  set.seed(1234)                                     
  score &lt;- runif(100, min = 0, max = 100)     
     
  Performance &lt;- function(x) {                       
    case_when(                                         
      is.na(x) ~ NA_character_,                          
      x &gt; 80   ~ 'Excellent',                            
      x &gt; 50   ~ 'Good',                                 
      TRUE     ~ 'Fail'                                  
    ) %&gt;% factor(levels=c('Excellent', 'Good', 'Fail'))
  }                                                  
                                                     
  performance &lt;- Performance(score)                  
  levels(performance)                                
  #&gt; [1] &quot;Excellent&quot; &quot;Good&quot;      &quot;Fail&quot;
  table(performance)                                 
  #&gt; performance
  #&gt; Excellent      Good      Fail 
  #&gt;        15        30        55
  </code></pre>