简体   繁体   English

根据R中的第一列对矩阵进行排序

[英]Sort matrix according to first column in R

I have a matrix with two columns of the following form:我有一个包含以下形式的两列的矩阵:

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

I would like to sort this matrix in increasing order based on the first column but I would like to keep the corresponding values in the second column.我想根据第一列按递增顺序对这个矩阵进行排序,但我想将相应的值保留在第二列中。

The output would look like this:输出将如下所示:

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

Read the data:读取数据:

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

And sort:并排序:

foo[order(foo$V1),]

This relies on the fact that order keeps ties in their original order.这依赖于order保持其原始顺序的事实。 See ?order .参见?order

Creating a data.table with key=V1 automatically does this for you.创建一个带有key=V1data.table自动为你做这件事。 Using Stephan's data foo使用 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

Be aware that if you want to have values in the reverse order, you can easily do so:请注意,如果您想以相反的顺序使用值,您可以轻松地这样做:

> 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

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

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

The accepted answer works like a charm unless you're applying it to a vector.除非您将其应用于向量,否则接受的答案就像一个魅力。 Since a vector is non-recursive, you'll get an error like this由于向量是非递归的,你会得到这样的错误

$ operator is invalid for atomic vectors

You can use [ in that case在这种情况下,您可以使用[

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

You do not need data.table .您不需要data.table

This is what you need A[order(A[,1]), ] , where A is the matrix of your data.这就是您需要的A[order(A[,1]), ] ,其中A是您的数据矩阵。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM