R:如何根据另一个对矩阵,data.frame或向量的行重新排序

Joh*_*n 19 r vector matrix dataframe

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
Run Code Online (Sandbox Code Playgroud)

如何重新排序test2以使行与test1的顺序相同?例如:

 test2
  [,1]
a    10
d    7
c    8
b    9
e    6
Run Code Online (Sandbox Code Playgroud)

我尝试使用重新排序函数:reorder(test1,test2)但我无法弄清楚正确的语法.我看到重新排序需要一个向量,我在这里使用矩阵.我的真实数据有一​​个字符向量,另一个是data.frame.我认为数据结构对于上面这个例子来说并不重要,我只需要帮助解决语法并使其适应我的实际问题.

Rob*_*man 20

test2 <- test2[rownames(test1),,drop=FALSE]
Run Code Online (Sandbox Code Playgroud)


Dir*_*tel 7

修复你的代码后修剪实际生成你的例子显示的内容(提示:test1有名字a,b,c,d,e;你的意思是a,d,c,b,1,如现在所示),这更容易归功于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> 
Run Code Online (Sandbox Code Playgroud)

他们关键在于match()做你想做的事:

R> match(row.names(test2), row.names(test1))
[1] 5 2 3 4 1
Run Code Online (Sandbox Code Playgroud)