title: Updating factor levels while filtering R data.frames
body: <p>I have a data.frame similar to below. I pre-process it by deleting rows that I am not interested in. Most of my columns are 'factors', whose 'levels' are not updated as I filter the data.frame.</p>
  
  <p>I can see that what I am doing below is not ideal. How do I get the factor levels update as I modify the data.frame? Below is a demonstration of what is going wrong.</p>
  
  <pre><code># generate data
  set.seed(2013)
  df &lt;- data.frame(site = sample(c("A","B","C"), 50, replace = TRUE),
                   currency = sample(c("USD", "EUR", "GBP", "CNY", "CHF"),50, replace=TRUE, prob=c(10,6,5,6,0.5)),
                   value = ceiling(rnorm(50)*10))
  
  # check counts to see there is one entry where currency =  CHF
  count(df, vars="currency")
  
  &gt;currency freq
  &gt;1      CHF    1
  &gt;2      CNY   13
  &gt;3      EUR   16
  &gt;4      GBP    6
  &gt;5      USD   14
  
  
  # filter out all entires where site = A, i.e. take subset of df
  df &lt;- df[!(df$site=="A"),]
  
  # check counts again to see how this affected the currency frequencies
  count(df, vars="currency")
  
  &gt;currency freq
  &gt;1      CNY   10
  &gt;2      EUR    8
  &gt;3      GBP    4
  &gt;4      USD   10
  
  # But, the filtered data.frame's levels have not been updated:
  levels(df$currency)
  
  &gt;[1] "CHF" "CNY" "EUR" "GBP" "USD"
  
  levels(df$site)
  
  &gt;[1] "A" "B" "C"
  </code></pre>
  
  <p><strong>desired outputs:</strong></p>
  
  <pre><code># levels(df$currency) = "CNY" "EUR" "GBP" "USD
  # levels(df$site) = "B" "C"
  </code></pre>