[R] Sorting a data frame by one of the variables

John Wilkinson (pipex) wilks at dial.pipex.com
Sun Oct 16 15:54:03 CEST 2005


Leaf,

using your example data as 'dat' below --

 dat<-read.table("clipboard",header=T)
 dat
     X    Y    Z
1 22.0 24.0  4.3
2  2.3  3.4  5.3
3 57.2 23.4 34.0

#to order the data frame by say X (for column 1)--

dat1<-dat[order(dat[,1]),]
 dat1
     X    Y    Z
2  2.3  3.4  5.3
1 22.0 24.0  4.3
3 57.2 23.4 34.0

--------------------------------------------
By way of interest if you wanted to order EVERY  column
in ascending order then you could do a loop ---

# to order  all cols of dat by rows (ascending)

dat2<-dat
 for (i in 1:3) dat2[,i]<-dat[order(dat[,i]),i]
 dat2
     X    Y    Z
1  2.3  3.4  4.3
2 22.0 23.4  5.3
3 57.2 24.0 34.0
------------------------------------------------

I hope that helps,

John


=====================================================
"Leaf Sun" wrote---

Dear all,

I have a date frame like this:

X   Y   Z
22	24	4.3
2.3	3.4	5.3
.....
....
57.2	23.4	34

What my purpose is: to sort the data frame by either X, Y or Z.
sample output is (sorted by X) :

X   Y   Z
2.3  3.4  5.3
.....
......
22 24  4.3
...
57.2  23.4  34

I have no idea how to use sort, order or rank functions. Please help me out.
Thanks!




More information about the R-help mailing list