[R] sorting matrix to match an ordered list

Marc Schwartz marc_schwartz at comcast.net
Tue Jan 27 21:46:44 CET 2009


on 01/27/2009 02:26 PM Nick Matzke wrote:
> Hi all,
> 
> This can't be very hard, but it is sticking me because I am a beginner.
>  Setup:
> 
> x = rbind(c(0,1,1), c(2,3,1), c(4,5,1))
> y = as.matrix(x)
> rownames(y) = c("a","b","c")
> colnames(y) = c("a","b","c")
> ordered_list = c("b", "c", "a")
> 
> How do I produce a new matrix, z, with the rows and columns both sorted
> in the order specified by ordered_list?
> 
> (I have a big 124x124 output matrix that comes out with the rows &
> columns in alphabetical order, I want them in a pre-specified order I
> can get from the input file, but the above is an example of the
> conceptual issue)
> 

The easiest way is probably:

> y[ordered_list, ordered_list]
  b c a
b 3 1 2
c 5 1 4
a 1 1 0

You are essentially using subsetting on the named rows and columns.

If the output matrix is based upon a cross-tabulation of two vectors or
factors, just set the factor levels in the order that you want the
output matrix to be created.

For example:

Vec1 <- sample(letters[1:4], 50, replace = TRUE)
Vec2 <- sample(letters[1:4], 50, replace = TRUE)

> table(Vec1, Vec2)
    Vec2
Vec1 a b c d
   a 5 5 5 3
   b 3 2 6 3
   c 2 2 3 3
   d 3 1 2 2

Vec1 <- factor(Vec1, levels = c("b", "c", "a", "d"))
Vec2 <- factor(Vec2, levels = c("b", "c", "a", "d"))

> table(Vec1, Vec2)
    Vec2
Vec1 b c a d
   b 2 6 3 3
   c 2 3 2 3
   a 5 5 5 3
   d 1 2 3 2


HTH,

Marc Schwartz




More information about the R-help mailing list