如何根据其他类别对因子水平进行排序?

时间:2011-10-16 20:51:18

标签: r dataframe

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

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中的某个级别始终与我的数据中的category中的级别相对应,那么如何相应地对名称级别进行排序?

2 个答案:

答案 0 :(得分:4)

这是你想要的吗?

> 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"

答案 1 :(得分:3)

我认为到目前为止,这可能比任何一种解决方案更清晰:

    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

如果你想重新考虑这个因素,也可以这样做,但是你不希望这个改变是永久性的。

相关问题