【问题标题】:How can I reorder the rows of a matrix, data.frame or vector according to another one如何根据另一行重新排序矩阵、data.frame 或向量的行
【发布时间】:2011-02-16 16:16:38
【问题描述】:
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) 但我无法找出正确的语法。我看到重新排序需要一个向量,而我在这里使用矩阵。我的真实数据有一​​个字符向量和另一个作为 data.frame。我认为对于上面的这个例子来说,数据结构并不重要,我只需要语法方面的帮助,并且可以根据我的实际问题调整它。

【问题讨论】:

    标签: r dataframe matrix vector


    【解决方案1】:
    test2 <- test2[rownames(test1),,drop=FALSE]
    

    【讨论】:

    • 为什么这对我的数据不起作用?我想做 test2[match(test2$column, test1$column),1,drop=FALSE] 因为我匹配的是列的值而不是 row.names
    【解决方案2】:

    在修复了您的代码被剪断以实际生成示例显示的内容后(提示: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] 因为我匹配的是列的值而不是row.names
    猜你喜欢
    • 2013-02-21
    • 1970-01-01
    • 1970-01-01
    • 2019-03-28
    • 2021-12-23
    • 2014-07-27
    • 2018-04-09
    • 2012-12-09
    • 2019-02-20
    相关资源
    最近更新 更多