【问题标题】:How to sort factor levels based on another category?如何根据另一个类别对因子水平进行排序?
【发布时间】:2011-12-08 21:21:46
【问题描述】:

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

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 中的同一级别,我如何对名称的级别进行相应的排序?

【问题讨论】:

  • 我自己找到了一个答案,使用interaction 函数进行排序,但我不能再发布 8 小时。代码是levels(df.test$name)[with(df.test, interaction(name, category, drop=T))]。与此同时,还有其他巧妙的答案吗?

标签: r dataframe


【解决方案1】:

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

    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

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

【讨论】:

  • 这更干净,但unique 调用对于除了这个简单数据之外的任何东西都是必不可少的。也许我也应该更明确地说明name 中的多个条目。我很抱歉。
【解决方案2】:

这是你想要的吗?

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

【讨论】:

  • 我会重新排列因子的水平而不是替换它们,但这基本上就是我要寻找的。 my.df$name &lt;- factor(my.df$name, levels=as.character(unique(my.df[order(my.df$category),]$name)))
猜你喜欢
  • 1970-01-01
  • 2021-11-14
  • 1970-01-01
  • 1970-01-01
  • 2021-11-17
  • 2021-02-21
  • 2020-05-15
  • 1970-01-01
相关资源
最近更新 更多