Skip to content

sorting matrix to match an ordered list

4 messages · Nick Matzke, Marc Schwartz, jim holtman

#
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)


Thanks!

Nick
#
on 01/27/2009 02:26 PM Nick Matzke wrote:
The easiest way is probably:
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)
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"))
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
#
try this:
a b c
a 0 1 1
b 2 3 1
c 4 5 1
b c a
b 3 1 2
c 5 1 4
a 1 1 0

        
On Tue, Jan 27, 2009 at 3:26 PM, Nick Matzke <matzke at berkeley.edu> wrote:

  
    
#
Didn't realize it was that simple...thanks!!
Nick
jim holtman wrote: