我需要在数据框中为变量排序观察的级别。当我用str()
查看变量的类型时,我注意到我的变量实际上是一个具有5个级别的因子。我订购它们没有运气。
我通常会创建自己的矢量并使用
对观察进行排名factor(x, ordered = TRUE, levels = c("low", "med", "high"))
但是,这次我试图在变量中组织五个序数类别。我没有成功使用
transform(x, variable_name = as.factor(x$variable_name, ordered=TRUE,
levels = c("low", "slightly low",
"medium", "slightly high", "high"))
或
transform(x, variable_name = factor(x$variable_name, ordered=TRUE,
levels = c("low", "slightly low",
"medium", "slightly high", "high"))
答案 0 :(得分:1)
如果我理解正确,您需要手动设置因子级别的顺序:
data(iris)
df <- iris
str(df$Species)
# Factor w/3 levels
df$Species <- ordered(df$Species,levels=c("virginica","versicolor","setosa"))
str(df$Species)
# Ord.factor w/3 levels