在不更改值顺序的情况下对因子的级别进行重新排序
我有包含一些数值变量和一些分类因子
变量的数据框。这些因素的级别顺序不是我想要的方式。
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
如果我改变级别的顺序,字母将不再与它们对应的数字在一起(从现在起我的数据完全是无稽之谈)。
levels(df$letters) <- c("d", "c", "b", "a")
df
# numbers letters
# 1 1 d
# 2 2 c
# 3 3 b
# 4 4 a
我只是想更改级别顺序,因此在绘图时,条形图会按所需的顺序显示 - 这可能与默认的字母顺序不同。
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
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
使用
factor
的levels
参数:Use the
levels
argument offactor
:更多,仅供记录
您可能还会发现有用的重新调整 和 combine_factor。
some more, just for the record
You may also find useful Relevel and combine_factor.
由于这个问题最后是活跃的,哈德利发布了他的新的用于操纵因素的
forcats
包,我发现它非常有用。 OP 数据框中的示例:反转级别:
添加更多级别:
以及许多更有用的
fct_xxx()
函数。Since this question was last active Hadley has released his new
forcats
package for manipulating factors and I'm finding it outrageously useful. Examples from the OP's data frame:To reverse levels:
To add more levels:
And many more useful
fct_xxx()
functions.因此,在 R 词典中,您想要的是仅更改给定因子变量的标签(即保留数据以及因子水平< /em>,不变)。
假设您只想更改数据点到标签的映射,而不是数据或因子模式(数据点如何分箱到单独的箱或因子值中,这可能有助于了解映射如何最初是在您最初创建因子时设置的,
规则很简单:
在levels[2]处给出标签,label[2]);
级别参数;或者
使用的值是在数据向量上调用unique的结果
传入(对于 data 参数);
使用的只是 levels 向量
so what you want, in R lexicon, is to change only the labels for a given factor variable (ie, leave the data as well as the factor levels, unchanged).
given that you want to change only the datapoint-to-label mapping and not the data or the factor schema (how the datapoints are binned into individual bins or factor values, it might help to know how the mapping is originally set when you initially create the factor.
the rules are simple:
at levels[2] is given the label, label[2]);
levels argument; or
value is used which is the result calling unique on the data vector
passed in (for the data argument);
used which is just the levels vector
我必须承认,处理 R 中的因子是一项相当特殊的工作......在重新排序因子级别时,您并没有重新排序基础数值。这里有一个小演示:
现在,如果您将此因子转换为数字,您将得到:
正如您所看到的...通过更改级别,您仅更改级别(谁会告诉,呃?),而不是数值!但是,当您按照 @Jonathan Chang 建议使用
factor
函数时,会发生不同的情况:您自己更改数值。您再次收到错误,因为您执行了级别,然后尝试使用因子重新级别。不要这样做!不要不要使用
级别
,否则你会把事情搞砸(除非你确切地知道你在做什么)。<我>
一个小建议:避免使用与 R 对象相同的名称来命名对象(
df
是 F 分布的密度函数,letters
给出小写字母)。在这种特殊情况下,您的代码不会有错误,但有时可能会……但这会造成混乱,我们不希望这样,不是吗?!? =)相反,使用类似这样的内容(我将再次从头开始):
请注意,您还可以使用
df
和 < 命名data.frame
。 code>letters 而不是g
,结果就OK了。实际上,这段代码与您发布的代码相同,只是名称发生了变化。这部分factor(dtf$letter,levels = letters[4:1])
不会抛出错误,但它可能会令人困惑!仔细阅读
?factor
手册!factor(g,levels = letter[4:1])
和factor(g, labels = letter[4:1])
之间有什么区别?levels(g) <- letters[4:1]
和g <- factor(g, labels = letter[4:1])
有什么相似之处?您可以使用 ggplot 语法,这样我们就可以在这方面为您提供更多帮助!
干杯!!!
编辑:
ggplot2实际上需要更改级别和值?嗯……我把这个挖出来……
Dealing with factors in R is quite peculiar job, I must admit... While reordering the factor levels, you're not reordering underlying numerical values. Here's a little demonstration:
Now, if you convert this factor to numeric, you'll get:
As you can see... by changing levels, you change levels only (who would tell, eh?), not the numerical values! But, when you use
factor
function as @Jonathan Chang suggested, something different happens: you change numerical values themselves.You're getting error once again 'cause you do
levels
and then try to relevel it withfactor
. Don't do it!!! Do not uselevels
or you'll mess things up (unless you know exactly what you're doing).One lil' suggestion: avoid naming your objects with an identical name as R's objects (
df
is density function for F distribution,letters
gives lowercase alphabet letters). In this particular case, your code would not be faulty, but sometimes it can be... but this can create confusion, and we don't want that, do we?!? =)Instead, use something like this (I'll go from the beginning once again):
Note that you can also name you
data.frame
withdf
andletters
instead ofg
, and the result will be OK. Actually, this code is identical with the one you posted, only the names are changed. This partfactor(dtf$letter, levels = letters[4:1])
wouldn't throw an error, but it can be confounding!Read the
?factor
manual thoroughly! What's the difference betweenfactor(g, levels = letters[4:1])
andfactor(g, labels = letters[4:1])
? What's similar inlevels(g) <- letters[4:1]
andg <- factor(g, labels = letters[4:1])
?You can put ggplot syntax, so we can help you more on this one!
Cheers!!!
Edit:
ggplot2
actually requires to change both levels and values? Hm... I'll dig this one out...我希望添加另一种情况,其中级别可以是带有数字和一些特殊字符的字符串:如下面的示例
x
的默认级别是:在这里,如果我们想根据数值对因子级别重新排序,在没有明确写出级别的情况下,我们能做的是
我希望这可以被视为对未来读者有用的信息。
I wish to add another case where the levels could be strings carrying numbers alongwith some special characters : like below example
The default levels of
x
is :Here if we want to reorder the factor levels according to the numeric value, without explicitly writing out the levels, what we could do is
I hope this can be considered as useful information for future readers.
这是我对给定数据帧的因子进行重新排序的函数:
用法:
reorderFactors(df, "my_col",desired_level_order = c("how","I","want"))
Here's my function to reorder factors of a given dataframe:
Usage:
reorderFactors(df, "my_col", desired_level_order = c("how","I","want"))
我会简单地使用级别参数:
I would simply use the levels argument:
添加另一种非常有用的方法,因为它使我们免于记住不同包中的函数。因素的级别只是属性,因此可以执行以下操作:
To add yet another approach that is quite useful as it frees us from remembering functions from differents packages. The levels of a factor are just attributes, so one can do the following: