如何根据另一个矩阵、数据框或向量重新排序行?

20
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相同?例如:

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

我尝试使用reorder函数:reorder(test1,test2),但我无法找到正确的语法。我发现reorder需要一个向量,而我在这里使用的是矩阵。我的真实数据有一个字符向量和另一个作为数据框架。我觉得数据结构对于上面的例子并不太重要,我只需要帮助解决语法问题,并能够将其适应到我的实际问题中。

2个回答

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

为什么这对我的数据不起作用?我想执行test2[match(test2$column, test1$column),1,drop=FALSE],因为我匹配的是列的值而不是行名称。 - chimpsarehungry

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> 

重点在于 match() 会做你想要的事情:
R> match(row.names(test2), row.names(test1))
[1] 5 2 3 4 1

为什么对我的数据没有用呢?我希望执行 test2[match(test2$column, test1$column),1,drop=FALSE],因为我匹配的是列的值而不是行名称。 - chimpsarehungry

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接