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 to order some of my columns (not rows) alphabetically
3 messages · Mark, David Scott
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
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