[R] multicolumn sort on dataframe?
Anne York
york at zipcon.net
Sat Mar 27 23:41:35 CET 2004
Forget about my previous post. That method only works in
very special cases. Use order with mutiple arguments.
On Sat, 27 Mar 2004, Anne York wrote:
AY > On Fri 26 Mar 2004, Jeff D. Hamann wrote:
AY >
AY > >I couldn't find any reference to this in the FAQ, but is it
AY > >possible to sort a dataframe by multiple columns?
AY >
AY > >I've created some code, similar to the following:
AY >
AY > >nspr.code <- sp.results$sp.code[order( sp.results$sp.code )]
AY > >nspr.tpa <- sp.results$tpa[order( sp.results$sp.code )]
AY >
AY > >nspr.code <- as.character( levels( nspr.code ) )[nspr.code]
AY > >nspr.tpa <- as.numeric( levels( nspr.tpa ) )[nspr.tpa]
AY >
AY > >hope <- as.data.frame( cbind( nspr.code, as.numeric(nspr.tpa) ) )
AY >
AY >
AY > A simple way to sort multiple columns is to paste them
AY > together and sort the resulting character vector. THat way
AY > you only have to do one sort. This is a very old method
AY > taught to me in the first computer course I ever took (date
AY > censored); the instructor attributed the method to Von
AY > Neumann but I have no reference.
AY >
AY > You have to be careful choosing the sep character in paste.
AY >
AY > Here is an example
AY >
AY >
AY > > set.seed(78)
AY > > foo = data.frame(x= sample(letters[1:3],5,replace=TRUE),
AY > y= sample(1:5,5,replace=TRUE))
AY > > foo
AY > x y
AY > 1 c 3
AY > 2 c 2
AY > 3 b 2
AY > 4 c 1
AY > 5 c 3
AY >
AY > Sorting on y and then by x:
AY >
AY > > my.order=order(foo.paste=paste(foo[,2],foo[,1],sep="/"))
AY > > my.order
AY > [1] 4 3 2 1 5
AY >
AY >
AY > > my.order=order(paste(foo[,1],foo[,2],sep="/"))
AY > > foo[my.order,]
AY > x y
AY > 3 b 2
AY > 4 c 1
AY > 2 c 2
AY > 1 c 3
AY > 5 c 3
AY > >
AY >
AY >
More information about the R-help
mailing list