如何根据另一个类别对因子水平进行排序?

发布于 2024-12-10 09:20:53 字数 624 浏览 0 评论 0原文

假设我有一个包含两个因素的数据框,我想对按第二类分组的一个因素的水平进行排序。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

找个人就嫁了吧 2024-12-17 09:20:53

这是你想要的吗?

> levels(my.df$name) <- as.character(unique(my.df[order(my.df$category),]$name))
> levels(my.df$name)
[1] "b" "c" "e" "f" "a" "d" "g" "h"

Is this what you want?

> levels(my.df$name) <- as.character(unique(my.df[order(my.df$category),]$name))
> levels(my.df$name)
[1] "b" "c" "e" "f" "a" "d" "g" "h"
箹锭⒈辈孓 2024-12-17 09:20:53

我认为这可能比迄今为止的任何一个解决方案都更清晰:

    my.df <-
structure(list(name = structure(1:8, .Label = c("a", "b", "c", 
"d", "e", "f", "g", "h"), class = "factor"), category = structure(c(1L, 
1L, 2L, 2L, 2L, 1L, 1L, 1L), .Label = c("A", "B"), class = "factor")), .Names = c("name", 
"category"), class = "data.frame", row.names = c("1", "2", "3", 
"4", "5", "6", "7", "8"))

 with(my.df, name[order(category)] )
[1] b d e h a c f g
Levels: a b c d e f g h

如果您想重新调整该因素,也可以这样做,但尚不清楚您是否希望这种更改是永久性的。

I think this might be cleaner than either of the solutions so far:

    my.df <-
structure(list(name = structure(1:8, .Label = c("a", "b", "c", 
"d", "e", "f", "g", "h"), class = "factor"), category = structure(c(1L, 
1L, 2L, 2L, 2L, 1L, 1L, 1L), .Label = c("A", "B"), class = "factor")), .Names = c("name", 
"category"), class = "data.frame", row.names = c("1", "2", "3", 
"4", "5", "6", "7", "8"))

 with(my.df, name[order(category)] )
[1] b d e h a c f g
Levels: a b c d e f g h

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文