简体   繁体   English

使用向量按列对大型R矩阵进行排序

[英]Sorting Large R Matrix by Column with Vector

I have a large R matrix that I would like to sort all the data by one column but that column needs to be sorted in an odd fashion (ie not ascending or descending). 我有一个很大的R矩阵,我想按一列对所有数据进行排序,但是该列需要以一种奇怪的方式排序(即,不能升序或降序)。 Here is an example: 这是一个例子:

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" 

Now I need to sort the matrix by column 2 using the vector: 现在,我需要使用向量按第2列对矩阵进行排序:

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

I know I need to use the order function because I want to keep the data from the other columns in the proper order as well. 我知道我需要使用order函数,因为我也想使其他列中的数据也保持正确的顺序。

Not sure if I got the question correctly, but you might try: 不知道我是否正确回答了问题,但是您可以尝试:

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" 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM