[R] multicolumn sort on dataframe?

Spencer Graves spencer.graves at pdf.com
Sat Mar 27 22:03:30 CET 2004


      "?order" includes the following: 

    order(..., na.last = TRUE, decreasing = FALSE)

    Arguments:     ...: a sequence of vectors, all of the same length.

    Examples:

     (ii <- order(x <- c(1,1,3:1,1:4,3), y <- c(9,9:1), z <-c(2,1:9)))
     ## 6  5  2  1  7  4 10  8  3  9
     rbind(x,y,z)[,ii] # shows the reordering (ties via 2nd & 3rd arg)

  [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
x    1    1    1    1    2    2    3    3    3     4
y    5    6    9    9    4    7    1    3    8     2
z    5    4    1    2    6    3    9    7    2     8

      hope this helps.  spencer graves

Anne York wrote:

>On Fri 26 Mar 2004, Jeff D. Hamann wrote:
>                                                                                
>  
>
>>I couldn't find any reference to this in the FAQ, but is it 
>>possible to sort a  dataframe by multiple columns?
>>    
>>
>                                                                                
>  
>
>>I've created some code, similar to the following:
>>    
>>
>                                                                                
>  
>
>>nspr.code <- sp.results$sp.code[order( sp.results$sp.code )]
>>nspr.tpa <- sp.results$tpa[order( sp.results$sp.code )]
>>    
>>
>                                                                                
>  
>
>>nspr.code <- as.character( levels( nspr.code ) )[nspr.code]
>>nspr.tpa <- as.numeric( levels( nspr.tpa ) )[nspr.tpa]
>>    
>>
>                                                                                
>  
>
>>hope <- as.data.frame( cbind( nspr.code, as.numeric(nspr.tpa) ) )
>>    
>>
>
>
>A simple way to sort multiple columns is to paste them 
>together and sort the resulting character vector. THat way 
>you only have to do one sort. This is a very old method 
>taught to me in the first computer course I ever took (date 
>censored); the instructor attributed the method to Von 
>Neumann but I have no reference. 
>
>You have to be careful choosing the sep character in paste. 
>
>Here is an example
>
>
>  
>
>>set.seed(78) 
>>foo = data.frame(x= sample(letters[1:3],5,replace=TRUE),
>>    
>>
>                   y= sample(1:5,5,replace=TRUE))
>  
>
>>foo
>>    
>>
>  x y
>1 c 3
>2 c 2
>3 b 2
>4 c 1
>5 c 3
>
>Sorting on y and then by x: 
>
>  
>
>>my.order=order(foo.paste=paste(foo[,2],foo[,1],sep="/"))
>>my.order
>>    
>>
>[1] 4 3 2 1 5
>
>
>  
>
>>my.order=order(paste(foo[,1],foo[,2],sep="/"))
>>foo[my.order,]
>>    
>>
>  x y
>3 b 2
>4 c 1
>2 c 2
>1 c 3
>5 c 3
>  
>
>
>______________________________________________
>R-help at stat.math.ethz.ch mailing list
>https://www.stat.math.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>  
>




More information about the R-help mailing list