2017-07-14 47 views
2

我有一個很大的R矩陣,我想按一列對所有數據進行排序,但該列需要以奇怪的方式排序(即不按升序或降序排列)。下面是一個例子:按列排序大R矩陣與矢量

test=matrix(data=c("A","B","C","D","E","E","F","F","F",1,2,2,3,4,5,6,6,6),ncol=2) 
> test 
     [,1] [,2] 
[1,] "A" "1" 
[2,] "B" "2" 
[3,] "C" "2" 
[4,] "D" "3" 
[5,] "E" "4" 
[6,] "E" "5" 
[7,] "F" "6" 
[8,] "F" "6" 
[9,] "F" "6" 

現在我需要的矩陣通過柱2使用矢量進行排序:

X = C(3,4,5,6,1,2)

我知道我需要使用順序函數,因爲我想保持來自其他列的數據的正確順序。

+0

有多大「大」? – Roland

回答

4

不知道如果我得到了正確的問題,但你可以嘗試:

test[order(match(test[,2],x)),]  
#  [,1] [,2] 
# [1,] "D" "3" 
# [2,] "E" "4" 
# [3,] "E" "5" 
# [4,] "F" "6" 
# [5,] "F" "6" 
# [6,] "F" "6" 
# [7,] "A" "1" 
# [8,] "B" "2" 
# [9,] "C" "2" 
+1

優秀的答案! – Prradep