Skip to content

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

3 messages · Mark, David Scott

#
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
#
On Thu, 25 Sep 2008, Mark Na wrote:

            
How about:
z a y
1 1 3 5
2 2 4 6
a y z
1 3 5 1
2 4 6 2

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
#
On Thu, 25 Sep 2008, Mark Na wrote:

            
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:
k1 k2 z a  y
1  1  3 5 7  9
2  2  4 6 8 10
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