Site icon R-bloggers

R: Drop factor levels in a dataset

[This article was first published on The Data Monkey, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
R has factors, which are very cool (and somewhat analogous to labeled levels in Stata). Unfortunately, the factor list sticks around even if you remove some data such that no examples of a particular level still exist

# Create some fake data
x < - as.factor(sample(head(colors()),100,replace=TRUE))
levels(x)
x < - x[x!="aliceblue"]
levels(x) # still the same levels
table(x) # even though one level has 0 entries!

The solution is simple: run factor() again:
x < - factor(x)
levels(x)

If you need to do this on many factors at once (as is the case with a data.frame containing several columns of factors), use drop.levels() from the gdata package:
x < - x[x!="antiquewhite1"]
df < - data.frame(a=x,b=x,c=x)
df < - drop.levels(df)

Now I’m going to quit monkeying around and get to sleep.

To leave a comment for the author, please follow the link and comment on their blog: The Data Monkey.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.