排序矩阵的第一列中指定行R - Sorting specified rows in a matrix by the first column in R

- 此内容更新于:2016-02-24
主题:

我有一个字符矩阵n行3列地铁。我有一个数值向量nmb一些数字,例如,4,5,6,我想只有地铁的行,由nmb包含的数字,我的第一列矩阵。所以我的情况我想离开我的矩阵没有除了行4、5、6这我想是按第一列排序,当然,写回矩阵地铁。我怎么能这样做呢?谢谢。

原文:

I have a character matrix mtr of n rows and 3 columns.

I have a numeric vector nmb with some numbers, for example, 4,5,6

I want to sort only the rows of mtr, the numbers of which are contained by nmb, by the first column of my matrix.

So in my case I want to leave my matrix untouched except for rows 4,5,6 which I would like to be sorted by the first column and, of course, written back into my matrix mtr.

How could I do that? Thanks.

解决方案:
你可以这样做:
原文:

You can do it in this way:

mtr[nmb,] <- mtr[order(mtr[nmb,1]),]
楼主:嗯,因为一些原因,它只是删除行定义的nmb……

(原文:Hm, for some reasons it just deleted rows defined by nmb...)

解决方案:
我认为这将会做一个例子:
原文:

I think this will do it

mtr[nmb,] <- mtr[nmb,][order(mtr[nmb,1]),]

An example:

nmb <- 4:6
mtr <- matrix(30:1, ncol=3)

> mtr
     [,1] [,2] [,3]
[1,]   30   20   10
[2,]   29   19    9
[3,]   28   18    8
[4,]   27   17    7
[5,]   26   16    6
[6,]   25   15    5
[7,]   24   14    4
[8,]   23   13    3
[9,]   22   12    2
[10,]   21   11    1

> mtr[nmb,] <- mtr[nmb,][order(mtr[nmb,1]),]

> mtr
     [,1] [,2] [,3]
[1,]   30   20   10
[2,]   29   19    9
[3,]   28   18    8
[4,]   25   15    5   <-
[5,]   26   16    6   <- sorted
[6,]   27   17    7   <-
[7,]   24   14    4
[8,]   23   13    3
[9,]   22   12    2
[10,]   21   11    1