对于单个因子变量
# 创建额外的因子水平 (gamma)
x <- factor(c("alpha","beta","alpha"), levels=c("alpha","beta","gamma"))
x
#> [1] alpha beta alpha
#> Levels: alpha beta gamma
# 移除额外的因子水平
x <- factor(x)
x
#> [1] alpha beta alpha
#> Levels: alpha beta
当导入数据之后,可能有一个混合因子变量和其他向量的数据框,然后想要重新计算所有因子的水平。可以使用droplevels()函数实现这一点。
# 创建一些因子的数据框 (有额外的因子水平)
df <- data.frame(
x = factor(c("alpha","beta","alpha"), levels=c("alpha","beta","gamma")),
y = c(5,8,2),
z = factor(c("red","green","green"), levels=c("red","green","blue"))
)
# 显示因子水平 (with extra levels)
df$x
#> [1] alpha beta alpha
#> Levels: alpha beta gamma
df$z
#> [1] red green green
#> Levels: red green blue
# 丢掉额外因子水平
df <- droplevels(df)
# 再次显示因子,现在没有额外的因子水平了
df$x
#> [1] alpha beta alpha
#> Levels: alpha beta
df$z
#> [1] red green green
#> Levels: red green
暂无数据