title: Drop unused factor levels in a subsetted data frame
body: <p>I have a data frame containing a <code>factor</code>. When I create a subset of this dataframe using <code>subset</code> or another indexing function, a new data frame is created.  However, the <code>factor</code> variable retains all of its original levels, even when/if they do not exist in the new dataframe.</p>
  
  <p>This causes problems when doing faceted plotting or using functions that rely on factor levels.</p>
  
  <p>What is the most succinct way to remove levels from a factor in the new dataframe?</p>
  
  <p>Here's an example:</p>
  
  <pre><code>df &lt;- data.frame(letters=letters[1:5],
                      numbers=seq(1:5))
  
  levels(df$letters)
  ## [1] "a" "b" "c" "d" "e"
  
  subdf &lt;- subset(df, numbers &lt;= 3)
  ##   letters numbers
  ## 1       a       1
  ## 2       b       2
  ## 3       c       3    
  
  # all levels are still there!
  levels(subdf$letters)
  ## [1] "a" "b" "c" "d" "e"
  </code></pre>