2014-04-12 19 views
0

此問題是this question的後續行動。如何將任意整數向量重新排列爲遞增順序

比方說,我有一個大的data.frame, df,列u, v。我希望以遞增順序對u, v的觀察到的變量交互進行編號,即從上到下穿過data.frame時看到它們的順序。

注意:假設df有一些現有的順序,所以臨時對其重新排序是不好的。

該帖子底部顯示的代碼運行良好,除了返回的結果向量不是遞增順序的。也就是說,而不是目前的:

# result is in decreasing order here: 
match(df$label, levels(df$label)) 
# [1] 5 6 3 7 4 7 2 2 1 1 

# but we'd like it to be in increasing order like this: 
# 1 2 3 4 5 4 6 6 7 7 

我一直在order(), rank(), factor(...ordered=T)等,並似乎沒有任何工作試驗。我必須忽略一些明顯的東西。有任何想法嗎?

注意:也不允許通過將u, v重新排序爲單獨因素來作弊。

set.seed(1234) 
df <- data.frame(u=sample.int(3,10,replace=T), v=sample.int(4,10,replace=T)) 
# u v 
# 1 1 3 
# 2 2 3 
# 3 2 2 
# 4 2 4 
# 5 3 2 
# 6 2 4 
# 7 1 2 
# 8 1 2 
# 9 2 1 
# 10 2 1 

(df$label <- factor(interaction(df$u,df$v), ordered=T)) 
# [1] 1.3 2.3 2.2 2.4 3.2 2.4 1.2 1.2 2.1 2.1 
# Levels: 2.1 < 1.2 < 2.2 < 3.2 < 1.3 < 2.3 < 2.4 

# This is ok except want increasing-order 
match(df$label, levels(df$label)) 
# [1] 5 6 3 7 4 7 2 2 1 1 

# no better.  
match(df$label, levels(df$label)[rank(levels(df$label))]) 
# [1] 6 7 1 4 3 4 5 5 2 2 
+0

它已經存在:'#...但我們希望像這樣遞增順序的結果向量:1 2 3 4 5 4 6 6 7 7' – smci

+0

'interaction'的輸出因子級別的編號是任意的。不要把它稱爲'1 2 3 4 5 4 6 6 7 7',而應該認爲它是E,F,C,G,D,G,B,B,A,A。唯一重要的是首先看到E(=> 1),F是第二個(=> 2)等等。所以我們的df $ label的矢量只需要重新編號(不知何故)爲1 2 3 4 5 4 6 6 7 7。我希望我清楚:S – smci

+0

無論如何,墨菲定律說我把我的頭撞了很久,然後我把它作爲一個問題發佈,我偶然發現了答案(下面)。 – smci

回答

0

呃!解決方案是添加interaction(... drop=T)。我仍然不完全明白爲什麼沒有這樣做會破壞事情。

# The original factor from interaction() had unused levels... 
str(df$label) 
# Factor w/ 12 levels "1.1","1.2","1.3",..: 3 7 6 8 10 8 2 2 5 5 

# SOLUTION 
df$label <- interaction(df$u,df$v, drop=T) 

str(df$label) 
# Factor w/ 7 levels "2.1","1.2","2.2",..: 5 6 3 7 4 7 2 2 1 1 

rank(unique(df$label)) 
# [1] 5 6 3 7 4 2 1 

我們將使用該等級(如上圖所示)來重新調整水平階觀察,如下對他們我們的矢量匹配之前:

# And now we get the desired result 
match(df$label, levels(df$label)[ rank(unique(df$label)) ]) 
# [1] 1 2 3 4 5 4 6 6 7 7