3

Possible Duplicate:
How to sort a dataframe by column(s) in R

I am trying to sort a data.frame by several columns

df<-data.frame("Sp1"=c(7,4,2),"Sp2"=c(6,2,1))
row.names(df)<-c("A01","A02","A03")

    Sp1 Sp2
A01   7   6
A02   4   2
A03   2   1

#I am using    

df[with(df, order("Sp1"))]

however this does nothing. Any ideas why? Thanks

Community
  • 1
  • 1
Elizabeth
  • 5,771
  • 16
  • 57
  • 88
  • You should use library(plyr) and the command - arrange(df, Sp1, Sp2) . Easy to remember and fast too. – RHelp Mar 19 '14 at 12:04

2 Answers2

6

Sp1 should not be quoted when you are using with. This would always just return 1 and thus just return your first row. Try this instead:

> df[order(df$Sp1),] 
    Sp1 Sp2
A03   2   1
A02   4   2
A01   7   6
> df[with(df, order(Sp1)), ]
    Sp1 Sp2
A03   2   1
A02   4   2
A01   7   6
A5C1D2H2I1M1N2O1R2T1
  • 177,446
  • 27
  • 370
  • 450
2

You can also try to use another bult-in function within doBy package:

# install.packages('doBy')
library(doBy)
orderBy(Sp1~Sp2, data=df)
    Sp1 Sp2
A03   2   1
A02   4   2
A01   7   6
Jilber Urbina
  • 50,760
  • 8
  • 101
  • 127