title: Reorder factor levels as numbers after extracting from alphanumeric subset
body: <p>I have a variant of a problem that <a href="https://stackoverflow.com/questions/2375587/reorder-levels-of-a-factor-without-changing-order-of-values">Reorder levels of a factor without changing order of values</a> does not answer:
  A variable in a dataset has mixed numbers and strings (I know that this is undesirable, but it's there), like <code>4 8 16 64 128 default</code>. When building the initial factor, the levels are kept in order (as found, which is sorted).</p>
  
  <p>However when I build subsets (requiring to clean up stale levels), the levels are sorted as strings, like <code>128 16 4 64 8</code>, even if the subset only contains numeric levels.  This is bad when doing a <code>boxplot(var ~ factor)</code>.</p>
  
  <p>Trying to use the solutions found in the question cited above (<code>factor(var, levels=sort(var)</code>), the levels ended with duplicates.</p>
  
  <p>Most similar answers assume the levels are known, which is not true in my case.  How can I sort the factor so that the levels are sorted.</p>
  
  <p>Example:</p>
  
  <pre><code>&gt; a&lt;-c(1,3,5,7,2)
  &gt; b&lt;-c(4,8,16,32,"default")
  &gt; df&lt;-data.frame(a, b)
  &gt; df$b&lt;-factor(df$b)
  &gt; str(df)
  'data.frame':   5 obs. of  2 variables:
   $ a: num  1 3 5 7 2
   $ b: Factor w/ 5 levels "16","32","4",..: 3 4 1 2 5
  &gt; ss&lt;-subset(df, b != "default")
  &gt; factor(ss$b)
  [1] 4  8  16 32
  Levels: 16 32 4 8
  &gt; factor(ss$b,levels=sort(ss$b))
  [1] 4  8  16 32
  Levels: 16 32 4 8
  ss$b&lt;-factor(ss$b,levels=sort(ss$b))
  boxplot(ss$a ~ ss$b)
  </code></pre>