Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R:按字母顺序重新排列因子的级别,但不按1排序_R - Fatal编程技术网

R:按字母顺序重新排列因子的级别,但不按1排序

R:按字母顺序重新排列因子的级别,但不按1排序,r,R,我想对因子的级别重新排序,以便新的顺序按字母顺序显示所有值,但我希望它是最后一个值 让我们假设我们有这个因素: x <- factor(c("Yes", "No", "Other", "Yes", "No", "Other")) > x [1] Yes No Other Yes No Other Levels: No Other Yes 但是如果我们有一个有几个不同级别的向量,我们不想再写它们,毕竟它们的顺序很好,除了一个 有没有更好的方法来解决这个问题而不必

我想对因子的级别重新排序,以便新的顺序按字母顺序显示所有值,但我希望它是最后一个值

让我们假设我们有这个因素:

x <- factor(c("Yes", "No", "Other", "Yes", "No", "Other"))

> x
[1] Yes   No    Other Yes   No    Other
Levels: No Other Yes
但是如果我们有一个有几个不同级别的向量,我们不想再写它们,毕竟它们的顺序很好,除了一个


有没有更好的方法来解决这个问题而不必从头开始编写整个向量?

您必须明确指定所需的新的
级别=
,但是有比键入所有级别更简单的方法来移动它们。比如说

x <- factor(c("Yes", "No", "Other", "Yes", "No", "Other"))
old.lvl<-levels(x)
x<-factor(x, levels=c(sort(old.lvl[old.lvl!="Other"], decreasing=T), "Other"))
x
# [1] Yes   No    Other Yes   No    Other
# Levels: Yes No Other

x您现在可以使用
forcats::fct_relevel轻松完成此操作

以你的例子:

> x <- factor(c("Yes", "No", "Other", "Yes", "No", "Other"))
> x
[1] Yes   No    Other Yes   No    Other
Levels: No Other Yes

# set "Yes" as first level and keep the rest alphabetically ordered
> x2 <- fct_relevel(x, "Yes")
> x2
[1] Yes   No    Other Yes   No    Other
Levels: Yes No Other
>x
[1] 是的,不是其他的是,不是其他的
级别:没有其他是
#将“是”设置为第一级,并按字母顺序排列其余部分
>x2x2
[1] 是的,不是其他的是,不是其他的
级别:是否其他

如果需要自定义订单,需要在级别中指定。也许
因子(v1,levels=c(排序(setdiff(unique(v1),'Other'),递减=TRUE),'Other'))
x <- factor(c("Yes", "No", "Other", "Yes", "No", "Other"))
old.lvl<-levels(x)
x<-factor(x, levels=c(sort(old.lvl[old.lvl!="Other"], decreasing=T), "Other"))
x
# [1] Yes   No    Other Yes   No    Other
# Levels: Yes No Other
> x <- factor(c("Yes", "No", "Other", "Yes", "No", "Other"))
> x
[1] Yes   No    Other Yes   No    Other
Levels: No Other Yes

# set "Yes" as first level and keep the rest alphabetically ordered
> x2 <- fct_relevel(x, "Yes")
> x2
[1] Yes   No    Other Yes   No    Other
Levels: Yes No Other