[R] lexicographic sort of ordered lists

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Fri Jul 18 23:54:06 CEST 2003


"J. P. Morgan" <jpmorgan at vt.edu> writes:

> Does anyone know how to execute the following sort problem in R? Matrix X
> has positive integer entries, and each column has been sorted in ascending
> order. The problem is now to order the columns lexicographically. For
> instance if the matrix X is
> 
>  
> 
> 1 2 1 1 2
> 
> 2 2 3 3 2
> 
> 3 5 5 4 2
> 
>  
> 
> then the result should be
> 
>  
> 
> 1 1 1 2 2
> 
> 2 3 3 2 2
> 
> 3 4 5 2 5
> 
>  
> 
> Let ONE be a vector of 1's of length ncol(X). The result in this example can
> be accomplished by
> 
>  
> 
> X=X[,order(ONE,X[1,],X[,2],X[,3])]

What's the ONE supposed to be good for??? Works just as well without
(after fixing the obvious typo):

> X[,order(X[1,],X[2,],X[3,])]
  V1 V4 V3 V5 V2
1  1  1  1  2  2
2  2  3  3  2  2
3  3  4  5  2  5


> but I need a method that will work regardless of k=number of rows of X. That
> is, the program must be able to accept any integer-valued matrix X for which
> each column is sorted, then permute columns accordingly. 

This should do it:

> X[,do.call("order",split(X,row(X)))]
  V1 V4 V3 V5 V2
1  1  1  1  2  2
2  2  3  3  2  2
3  3  4  5  2  5

(is there a better way of obtaining a list containing the rows of a
matrix?)

-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907




More information about the R-help mailing list