如何根据另一个类别对因子水平进行排序?
假设我有一个包含两个因素的数据框,我想对按第二类分组的一个因素的水平进行排序。
name <- letters[1:8]
category <- factor(sample(1:2, 8, replace=T), labels=c("A", "B"))
my.df <- data.frame(name=name, category=category)
因此,数据框看起来类似于:
name category
1 a A
2 b A
3 c B
4 d B
5 e B
6 f A
7 g A
8 h A
并且 levels(my.df$name)
的输出为:
[1] "a" "b" "c" "d" "e" "f" "g" "h"
假设 name
中的级别始终对应于 name
中的同一级别code>category 在我的数据中,如何相应地对名称级别进行排序?
Say I have a data frame with two factors in there and I want to sort the levels of one factor grouped by the second category.
name <- letters[1:8]
category <- factor(sample(1:2, 8, replace=T), labels=c("A", "B"))
my.df <- data.frame(name=name, category=category)
So the data frame looks similar to:
name category
1 a A
2 b A
3 c B
4 d B
5 e B
6 f A
7 g A
8 h A
and the output of levels(my.df$name)
is:
[1] "a" "b" "c" "d" "e" "f" "g" "h"
Assuming that a level in name
always corresponds to the same level in category
in my data, how can I sort the levels of name accordingly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是你想要的吗?
Is this what you want?
我认为这可能比迄今为止的任何一个解决方案都更清晰:
如果您想重新调整该因素,也可以这样做,但尚不清楚您是否希望这种更改是永久性的。
I think this might be cleaner than either of the solutions so far:
If you wanted to relevel the factor, that could be done as well, but it wasn't clear that you wanted that change to be permanent.