给定一个向量,其中“b”始终是其中的一个元素,如何使“b”具有比所有其他因子更高的级别(无需重新排序其他因子相对于彼此的顺序)?
例如
> set.seed(1) # for reproducibility
> df<-data.frame(x=letters[c(2,sample(4,4,replace=TRUE))])
> df
x
1 b
2 b
3 b
4 c
5 d
> levels(df$x)
[1] "b" "c" "d"
我不确定我问的是否正确,但我该如何做到这一点 levels(df$x) = "c","d","b"
换句话说,我希望“b”始终显示在最后。
最佳答案
# Make some data
x <- c("a", "b", "c", "b", "a")
x <- factor(x)
> x
[1] a b c b a
Levels: a b c
我们可以按照我们想要的顺序重新指定因子
# save the current levels
lev <- levels(x)
# Find the one we want
# So change this to specify the level you want to be last
val <- which(lev == "b")
# Remake the factor specifying the order we want
x <- factor(x, levels = c(lev[-val], lev[val]))
> x
[1] a b c b a
Levels: a c b
关于r - 如何使向量中的特定因子的水平高于其他所有因子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20790730/