用矢量对列进行大R矩阵排序

时间:2017-07-14 15:10:41

标签: r sorting matrix

我有一个大的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)

我知道我需要使用order函数,因为我还希望以正确的顺序保存其他列中的数据。

1 个答案:

答案 0 :(得分: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"