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

From: John Wilkinson (pipex) <wilks_at_dial.pipex.com>
Date: Sun 16 Oct 2005 - 23:54:03 EST


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!



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Sun Oct 16 23:50:39 2005

This archive was generated by hypermail 2.1.8 : Sun 23 Oct 2005 - 18:56:19 EST