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

前端 未结 2 1540
难免孤独
难免孤独 2021-02-04 03:09
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(\         


        
2条回答
  •  一整个雨季
    2021-02-04 03:50

    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
    

提交回复
热议问题