R:如何根据另一个重排序矩阵,数据框架或向量的行 [英] R: How can I reorder the rows of a matrix, data.frame or vector according to another one
本文介绍了R:如何根据另一个重排序矩阵,数据框架或向量的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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 test1,test2),但我找不到正确的语法。我看到reorder需要一个向量,我在这里使用一个矩阵。我的真实数据有一个字符向量,另一个是数据框。我认为数据结构对于上面这个例子来说并不重要,我只需要帮助语法,并且可以适应我的真正问题。
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]
这篇关于R:如何根据另一个重排序矩阵,数据框架或向量的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文