如何根据另一行重新排列矩阵

如何根据另一行重新排列矩阵

本文介绍了如何根据另一行重新排列矩阵,data.frame或vector的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

如何重新排列test2以便行与test1相同?例如

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

我尝试将reorder函数用于:reorder(test1,test2),但是我找不到正确的语法.我看到重新排序需要一个向量,而我在这里使用矩阵.我的真实数据具有一个字符向量,而另一个则作为data.frame.我认为对于上面的示例来说,数据结构并不太重要,我只需要语法方面的帮助即可使其适应我的实际问题.

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.

推荐答案

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

这篇关于如何根据另一行重新排列矩阵,data.frame或vector的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 17:57