How to order some of my columns (not rows) alphabetically
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
How about:
df <- data.frame(z=1:2,a=3:4,y=5:6) df
z a y 1 1 3 5 2 2 4 6
sortdf <- df[,sort(names(df))] sortdf
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