1

This is a very embarrassing question, but I cannot understand the result of the following:

> order(c(3,1,2))
[1] 2 3 1

So, it's saying the ordered sequence is 2, 3, 1? How?

Gavin Simpson
  • 164,190
  • 25
  • 377
  • 440
Heisenberg
  • 7,626
  • 10
  • 49
  • 96

1 Answers1

4
> a <- c(30,10,20)     # sample data
> sort(a)              # sort returns your vector sorted
[1] 10 20 33
> order(a)             # order returns the *indices* in the sorted vector
[1] 2 3 1
> a[order(a)]          # so if you select your numbers with those indices
[1] 10 20 30           # you get your vector sorted
Julián Urbano
  • 8,290
  • 1
  • 29
  • 52
  • How can this be extended to dataframes? I am having trouble using order to sort a table based on two columns – Kory Jul 29 '15 at 14:58
  • @Kory You can use `order` with several parameters. It'll sort w.r.t. to the first one, then the second one, etc. For instance, `df[order(df$a, df$b),]` will sort by column `a` and then by column `b`. – Julián Urbano Jul 29 '15 at 18:45