Skip to content
Prev 315021 / 398506 Next

sort matrix based on a specific order

You can use factor() or match() to specify a particular order.  E.g.,
  > mat<-cbind(c('w','x','y','z'),c('a','b','c','d'))
  > ind<-c('c','b','d','a')
  > mat[ order(match(mat[,2], ind)), ]
       [,1] [,2]
  [1,] "y"  "c" 
  [2,] "x"  "b" 
  [3,] "z"  "d" 
  [4,] "w"  "a" 
  > mat[ order( factor(mat[,2], levels=ind) ), ]
       [,1] [,2]
  [1,] "y"  "c" 
  [2,] "x"  "b" 
  [3,] "z"  "d" 
  [4,] "w"  "a"

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com