user1723765
user1723765

Reputation: 6399

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

Upvotes: 52

Views: 167411

Answers (6)

Ryan Olson
Ryan Olson

Reputation: 21

If your data is in a matrix named foo, the line you would run is

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

The order(foo[,1]) expression returns the elements from the first column of foo in ascending order. The foo[x, ] expression returns the rows of foo ordered according to the vector of indices x.

Upvotes: 2

shubhamgoel27
shubhamgoel27

Reputation: 1439

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"]),]

Upvotes: 0

Vassilis Chasiotis
Vassilis Chasiotis

Reputation: 439

You do not need data.table.

This is what you need A[order(A[,1]), ], where A is the matrix of your data.

Upvotes: 1

Gabriel123
Gabriel123

Reputation: 456

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

Upvotes: 10

Arun
Arun

Reputation: 118799

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

Upvotes: 13

Stephan Kolassa
Stephan Kolassa

Reputation: 8267

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.

Upvotes: 53

Related Questions