[R] lexicographic sort of ordered lists
Duncan Murdoch
dmurdoch at pair.com
Fri Jul 18 22:30:48 CEST 2003
On Fri, 18 Jul 2003 15:56:31 -0400, "J. P. Morgan" <jpmorgan at vt.edu>
wrote :
>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
...
>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.
You could do it in a loop, if you had a "stable" order() function. I
don't know if the standard order() is stable; here's one that is
stable:
stableorder <- function(x, ...) order(x, ...,1:length(x))
Then the idea is to loop from the last row to the first, sorting
columns in a stable way:
lexico <- function(X) {
for (i in nrow(X):1) {
X <- X[, stableorder(X[i,])]
}
X
}
(I just tried this with the regular order(), and got the same result,
so order() might be stable, but I wouldn't trust it to be...)
Duncan Murdoch
More information about the R-help
mailing list