【问题标题】:Sort matrix according to first column in R根据R中的第一列对矩阵进行排序
【发布时间】:2012-12-30 20:23:30
【问题描述】:

我有一个包含以下形式的两列的矩阵:

1 349
1 393
1 392
4 459
3 49
3 32
2 94

我想根据第一列按升序对该矩阵进行排序,但我想将相应的值保留在第二列中。

输出如下所示:

1 349
1 393
1 392
2 94
3 49
3 32
4 459

【问题讨论】:

标签: r


【解决方案1】:

读取数据:

foo <- read.table(text="1 349
  1 393
  1 392
  4 459
  3 49
  3 32
  2 94")

然后排序:

foo[order(foo$V1),]

这依赖于order 保持联系的原始顺序这一事实。见?order

【讨论】:

  • 好主意,+1。或者foo[order(foo$V1,foo$V2),]with 斗争的人(像我一样)。
  • 如果我想按降序排序呢? // 我试过了但是不行:foo[order(foo$V1), decreasing = TRUE]
  • decreasing 参数需要进入order 函数,而不是[ 运算符:foo[order(foo$V1,decreasing=TRUE),]
  • foo[order(foo$V1),]foodata.frame 时有效。如果foomatrix 使用foo[order(foo[, "V1"]),]
  • 答案适用于 data.frame 而不是@Wakan Tanka 指出的矩阵
【解决方案2】:

使用key=V1 创建data.table 会自动为您完成此操作。使用 Stephan 的数据foo

> require(data.table)
> foo.dt <- data.table(foo, key="V1")
> foo.dt
   V1  V2
1:  1 349
2:  1 393
3:  1 392
4:  2  94
5:  3  49
6:  3  32
7:  4 459

【讨论】:

  • 很好,+1!是否记录了data.table 以原始顺序保持键中的关系?如果没有,这可能会在data.table 的后续版本中发生变化吗?如果这些更改破坏了使用较旧软件包版本编写的脚本,则很难找到此类更改。
  • +1。 @StephanKolassa,同意。是的,这是记录并保证的。来自?data.tableThe order of the rows within each group is preserved, as is the order of the groups.。在?setkey(在它自己的段落中):The sort is stable; i.e., the order of ties (if any) is preserved.
  • @Arun,OP 曾询问有关对matrix 进行排序的问题;转换为data.table 并比直接使用矩阵的任何其他方法更好(=更快)排序?我的印象是,尽可能处理矩阵比data.xxx 对象之类的列表要快。
【解决方案3】:

请注意,如果您想以相反的顺序获取值,您可以轻松地这样做:

> example = matrix(c(1,1,1,4,3,3,2,349,393,392,459,49,32,94), ncol = 2)
> example[order(example[,1], decreasing = TRUE),]
     [,1] [,2]
[1,]    4  459
[2,]    3   49
[3,]    3   32
[4,]    2   94
[5,]    1  349
[6,]    1  393
[7,]    1  392

【讨论】:

    【解决方案4】:

    如果您的数据位于名为foo 的矩阵中,您将运行的行是

    foo.sorted=foo[order[foo[,1]]

    【讨论】:

      【解决方案5】:

      除非您将其应用于向量,否则接受的答案就像一个魅力。由于向量是非递归的,你会得到这样的错误

      $ operator is invalid for atomic vectors
      

      在这种情况下你可以使用[

      foo[order(foo["V1"]),]
      

      【讨论】:

        【解决方案6】:

        你不需要data.table

        这就是您需要的A[order(A[,1]), ],其中A 是您的数据矩阵。

        【讨论】:

          猜你喜欢
          • 2018-04-09
          • 2020-11-19
          • 1970-01-01
          • 2019-03-28
          • 2020-11-04
          • 2014-07-12
          • 1970-01-01
          • 2013-04-09
          • 1970-01-01
          相关资源
          最近更新 更多