How can I reorder the rows of a matrix, data.frame or vector according to another one

25,502

Solution 1

test2 <- test2[rownames(test1),,drop=FALSE]

Solution 2

After fixing your code snipped to actually generate what your example shows (hint: test1 had names a,b,c,d,e; you meant a,d,c,b,1 as it shows now), this was easier thanks to match():

R> test2[match(row.names(test2), row.names(test1)),1,drop=FALSE]
  [,1]
a   10
d    7
c    8
b    9
e    6
R> 

They key here is that match() does what you want:

R> match(row.names(test2), row.names(test1))
[1] 5 2 3 4 1
Share:
25,502
John
Author by

John

Updated on March 04, 2020

Comments

  • John
    John about 4 years
    test1 <- as.matrix(c(1, 2, 3, 4, 5))
    row.names(test1) <- c("a", "d", "c", "b", "e") 
    
    test2 <- as.matrix(c(6, 7, 8, 9, 10))
    row.names(test2) <- c("e", "d", "c", "b", "a") 
    
      test1
      [,1]
    a    1
    d    2
    c    3
    b    4
    e    5
    
     test2
      [,1]
    e    6
    d    7
    c    8
    b    9
    a   10
    

    How can I reorder test2 so that the rows are in the same order as test1? e.g.

     test2
      [,1]
    a    10
    d    7
    c    8
    b    9
    e    6
    

    I tried to use the reorder function with: reorder (test1, test2) but I could not figure out the correct syntax. I see that reorder takes a vector, and I'm here using a matrix. My real data has one character vector and another as a data.frame. I figured that the data structure would not matter too much for this example above, I just need help with the syntax and can adapt it to my real problem.

  • chimpsarehungry
    chimpsarehungry over 11 years
    Why does this not work for my data? I want to do test2[match(test2$column, test1$column),1,drop=FALSE] because what i am matching by is the values of the columns not the row.names
  • chimpsarehungry
    chimpsarehungry over 11 years
    Why does this not work for my data? I want to do test2[match(test2$column, test1$column),1,drop=FALSE] because what i am matching by is the values of the columns not the row.names