r - 如何使向量中的特定因子的水平高于其他所有因子?

标签 r

给定一个向量,其中“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/

相关文章:

r - 使用 model.frame 和公式提取数据框

r - 来自 Shell 的 R CMD BATCH 模式中的参数

r - 如何读取缺少第一个列名的数据表?

r - 如何在 RSTudio 中为 Flex 仪表板选项卡的标签选择颜色?

r - 在 Glmnet 和 dotCall64 中使用 R 中的长向量

r - 如何将变量重新编码为数字?

r - 图片未显示在 Shiny 应用程序 R 中

r - 如何在两条线之间填充不同的颜色? (原来是: fill geom_polygon with different colors above and below y = 0 (or any other value)?)

使用 R 通过 ssl 读取 csv 文件

r - 如何用数千和数百万替换 "k"和 "m"?