2011-10-16 29 views
2

說我有一個有兩個因素的數據框在那裏,我想排序由第二類分組的一個因素的水平。如何根據其他類別對因素水平進行排序?

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在我的數據中,我怎樣才能對名稱的級別進行相應的排序?

+0

我找到了一個答案,我自己使用「交互」功能來排序,但我不能發佈另一個8小時。代碼是'levels(df.test $ name)[(df.test,interaction(name,category,drop = T))]''。與此同時,還有其他任何圓滑的答案嗎? – Midnighter

回答

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

我會重新排列因子的水平,而不是取代它們,但基本上我正在尋找。 'my.df $ name < - factor(my.df $ name,levels = as.character(unique(my.df [order(my.df $ category),] $ name)))' – Midnighter

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 

如果你想relevel因素,可以做的很好,但它並不清楚你希望這種改變是永久的。

+0

這樣更乾淨但是除了這個簡單的數據之外,「唯一」調用是非常重要的。也許我應該更清楚'name'中的多個條目。我道歉。 – Midnighter

相關問題