How can I drop unused levels from a data frame?

爱⌒轻易说出口 提交于 2019-11-27 06:48:35

There's a recently added function in R for this:

y <- droplevels(y)

Just do y$let <- factor(y$let). Running factor on an existing factor variable will reset the levels to only those that are present.

Adding to Hong Ooi's answer, here is an example I found from R-Bloggers.

# 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)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!