Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort matrix according to first column in R

Tags:

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 
like image 843
user1723765 Avatar asked Jan 16 '13 13:01

user1723765


People also ask

How do I sort a matrix in R?

There might be multiple reasons to sort a matrix such as we want to convert the matrix to a data frame, the data stored in matrix needs to be sorted prior to matrix calculations so that the view of the result after calculations becomes clearer, etc. To sort a matrix based on one column, we can use order function.

How do you sort a column by a matrix?

On the "Modeling" tab of the Data view, click the "Sort by Column" button and choose [Sort Order]. Go back to the Report view and add your matrix, adding row, column, and value fields. If the columns are sorted in the order you wanted, you win!

How do you arrange a matrix in ascending order in R?

To sort a data frame in R, use the order( ) function. By default, sorting is ASCENDING. Prepend the sorting variable by a minus sign to indicate DESCENDING order.

How do you find the first column of a matrix in R?

If you want to select all elements of a row or a column, no number is needed before or after the comma, respectively: my_matrix[,1] selects all elements of the first column. my_matrix[1,] selects all elements of the first row.


2 Answers

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. See ?order.

like image 194
Stephan Kolassa Avatar answered Sep 17 '22 13:09

Stephan Kolassa


Creating a data.table with key=V1 automatically does this for you. Using Stephan's data 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 
like image 31
Arun Avatar answered Sep 19 '22 13:09

Arun