在不改变值顺序的情况下重新排序因子的级别 [英] Reorder levels of a factor without changing order of values

查看:64
本文介绍了在不改变值顺序的情况下重新排序因子的级别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些数值变量和一些分类factor变量的数据框.这些因素的级别顺序不是我想要的.

I have data frame with some numerical variables and some categorical factor variables. The order of levels for those factors is not the way I want them to be.

numbers <- 1:4
letters <- factor(c("a", "b", "c", "d"))
df <- data.frame(numbers, letters)
df
#   numbers letters
# 1       1       a
# 2       2       b
# 3       3       c
# 4       4       d

如果我改变级别的顺序,字母不再是对应的数字(从现在开始我的数据完全是胡说八道).

If I change the order of the levels, the letters no longer are with their corresponding numbers (my data is total nonsense from this point on).

levels(df$letters) <- c("d", "c", "b", "a")
df
#   numbers letters
# 1       1       d
# 2       2       c
# 3       3       b
# 4       4       a

我只是想更改 level 顺序,因此在绘图时,条形按所需顺序显示 - 这可能与默认字母顺序不同.

I simply want to change the level order, so when plotting, the bars are shown in the desired order - which may differ from default alphabetical order.

推荐答案

使用factorlevels参数:

df <- data.frame(f = 1:4, g = letters[1:4])
df
#   f g
# 1 1 a
# 2 2 b
# 3 3 c
# 4 4 d

levels(df$g)
# [1] "a" "b" "c" "d"

df$g <- factor(df$g, levels = letters[4:1])
# levels(df$g)
# [1] "d" "c" "b" "a"

df
#   f g
# 1 1 a
# 2 2 b
# 3 3 c
# 4 4 d

这篇关于在不改变值顺序的情况下重新排序因子的级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆