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

R 如何从数据帧中删除未使用的级别?,r,levels,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') 但我不想再出现a。如果我尝试这样做: levels(y$let) <- factor(y$let) 我知道我可以做xtabs(~y$let,d

给定以下模拟数据:

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')
但我不想再出现
a
。如果我尝试这样做:

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


问题是:如何自动更改
级别(y$let)
,使其不显示创建子集时删除的级别?在这种情况下,如何使其显示
[1]“b”“c”“d”“e”

只需执行
y$let在R中最近添加了一个函数:

y <- droplevels(y)

y补充Hong Ooi的答案,我从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)
#创建一些虚假数据

重复问题中的获胜答案不如这里的答案好。另一个应该标记为此的副本,因为这是一个更好的答案
y <- droplevels(y)
# 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)