Skip to content
Prev 181599 / 398502 Next

Sort matrix by column 1 ascending then by column 2 decending

It's a very interesting problem. I just wrote a function for it:

order.matrix <- function(m, columnsDecreasing = c('1'=FALSE), rows = 1:nrow(m))
{
  if (length(columnsDecreasing) > 0)
  {
    col <- as.integer(names(columnsDecreasing[1]));
    values <- sort(unique(m[rows, col]), decreasing=columnsDecreasing[1]);
    unlist(sapply(values, function(x) order.matrix(m,
columnsDecreasing[-1], which((1:nrow(m) %in% rows) & (m[,
col]==x)))));
  }
  else
  {
    rows;
  }
}

For instance:
[,1] [,2]
[1,]    2  0.5
[2,]    1  0.3
[3,]    1  0.5
[4,]    3  0.2
[,1] [,2]
[1,]    1  0.3
[2,]    1  0.5
[3,]    2  0.5
[4,]    3  0.2
[,1] [,2]
[1,]    1  0.5
[2,]    1  0.3
[3,]    2  0.5
[4,]    3  0.2

Any comment is welcome! ;)
On Wed, May 27, 2009 at 11:04 PM, Linlin Yan <yanlinlin82 at gmail.com> wrote: