2

I have a data frame that looks like the following

foo <- read.table(text="1 VA
  1 PE
  1 CE
  4 PE
  3 PE
  3 CE
  2 PE")

Now I want to sort the data frame according to first row first, which I can do by simply

foo[order(foo$V1),]

which gives the result :

   V1 V2
 1  1 VA
 2  1 PE
 3  1 CE
 7  2 PE
 5  3 PE
 6  3 CE
 4  4 PE

But my problem now is I want to keeping the sorted result in V1 same, I want to sort it according to second column. The results should look something like

   V1 V2
 1  1 CE
 2  1 PE
 3  1 VA
 7  2 PE
 5  3 CE
 6  3 PE
 4  4 PE

where first column is as it is but second column, V2 is also sorted something similar to

sort -k1 -k2 

in unix

eddi
  • 49,088
  • 6
  • 104
  • 155
discipulus
  • 2,665
  • 3
  • 34
  • 51
  • 2
    I suggest reading through [this answer](http://stackoverflow.com/a/29331287/559784) for a fast and memory efficient data.table solution. `setorder()` works with `data.frames` too from v1.9.5+. – Arun Apr 16 '15 at 09:05

1 Answers1

2

you can use the package dplyr with arrange like

library(dplyr)
arrange(foo, V1,V2) # sort according to V1 first, then V2
  V1 V2
1  1 CE
2  1 PE
3  1 VA
4  2 PE
5  3 CE
6  3 PE
7  4 PE
Mamoun Benghezal
  • 5,264
  • 7
  • 28
  • 33