[R] How to order some of my columns (not rows) alphabetically

David Scott d.scott at auckland.ac.nz
Fri Sep 26 01:49:37 CEST 2008


On Thu, 25 Sep 2008, Mark Na wrote:

> Hello,
>
> I have a dataframe with 9 columns, and I would like to sort (order) the 
> right-most eight of them alphabetiaclly, i.e.:
>
> ID1 ID2 F G A B C E D
>
> would become
>
> ID1 ID2 A B C D E F G
>
> Right now, I'm using this code:
>
> attach(data)
> data<-data.frame(ID1,ID2,data[,sort(colnames(data)[3:9])])
> detach(data)
>
> but that's not very elegant. Ideally I could specify which columns to sort 
> and which to leave "as is" (but my attempts to do so have failed).
>
> Thank you,
>
> Mark
>

OK, my first response was a bit quick and ignored the need to keep the 
first two columns.

The major point is that you can avoid the attach/detach if you use names 
in the subsetting:

> df <- data.frame(k1=1:2,k2=3:4,z=5:6,a=7:8,y=9:10)
> df
   k1 k2 z a  y
1  1  3 5 7  9
2  2  4 6 8 10
> sortdf <- df[,c(names(df)[1:2],sort(names(df)[3:5]))]
> sortdf
   k1 k2 a  y z
1  1  3 7  9 5
2  2  4 8 10 6

The rearrangement of the columns is just a one-liner and (in my view at 
least) easy to read and understand

David Scott

_________________________________________________________________
David Scott	Department of Statistics, Tamaki Campus
 		The University of Auckland, PB 92019
 		Auckland 1142,    NEW ZEALAND
Phone: +64 9 373 7599 ext 86830		Fax: +64 9 373 7000
Email:	d.scott at auckland.ac.nz

Graduate Officer, Department of Statistics
Director of Consulting, Department of Statistics



More information about the R-help mailing list