-1

我创建了一个模型矩阵。一些变量是分类变量。过滤数据后,某些级别不再在数据集中。如何删除未使用的级别?我可以对分类变量应用因子函数吗?

4

1 回答 1

3

您可以使用基础 Rdroplevels中的函数。让x成为您的因素/分类变量:

x <- as.factor(c("cat", "dog","cat", "gator"))
x
# [1] cat   dog   cat   gator
# Levels: cat dog gator

# somewhere in analysis you removed the only entry for a level
x <- x[x!= "gator"]     
x
# [1] cat dog cat
# Levels: cat dog gator

droplevels(x)
# [1] cat dog cat
# Levels: cat dog

有关详细信息,请参阅droplevels R 文档

于 2018-07-02T15:14:59.377 回答