如何从数据框中删除未使用的级别?

时间:2013-06-20 15:39:54

标签: r levels

给出以下模拟数据:

set.seed(123)
x <- data.frame(let = sample(letters[1:5], 100, replace = T), 
                num = sample(1:10, 100, replace = T))
y <- subset(x, let != 'a')

创建y$let产量表

a  b  c  d  e 
0 20 21 22 18

但我不想让a显示出来。如果我尝试这样做:

levels(y$let) <- factor(y$let)

我弄乱频率,因为现在table(y$let)给了我

b  d  c  e 
0 20 21 40 

我知道我可以做xtabs(~ y$let, drop.unused.levels = T)并解决问题,但它没有重置核心的变量级别(这对我来说很重要,因为这是我正在做的早期变化到将在整个分析过程中继续进行的数据集)。此外,xtabs是与table不同的类,这会让我在项目后期感到头疼。

问题是:如何自动更改levels(y$let),以便它不显示创建子集时丢弃的级别?在这种情况下,如何让它显示[1] "b" "c" "d" "e"

3 个答案:

答案 0 :(得分:114)

最近在R中添加了一个功能:

y <- droplevels(y)

答案 1 :(得分:22)

y$let <- factor(y$let)。在现有因子变量上运行factor会将级别重置为仅存在的级别。

答案 2 :(得分:2)

添加到Hong Ooi的回答,here is我从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)