Reputation: 23
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 (i.e. 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.
Upvotes: 2
Views: 287
Reputation: 24520
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"
Upvotes: 4