简体   繁体   中英

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). 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:

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.

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" 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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