ONeillMB1
ONeillMB1

Reputation: 343

Order Matrices or Dists by dimnames

I am trying to perform Mantel tests for which I have a genetic distance matrix and a physical distance matrix. Due to how these matrices were generated, their 'order's are jumbled with respect to one another. Surprisingly, I am finding it difficult to order these matrices by their row/column names (i.e. the dimnames or dimension names). Any help would be greatly appreciated.

Below is a dummy sample set:

d1 = matrix(c(0,1,2,1,0,3,2,3,0),nrow=3, ncol=3)
rownames(d1) <- c("A","B","C")
colnames(d1) <- c("A","B","C")

d3 = matrix(c(0,.2,.3,.2,0,.1,.3,.1,0),nrow=3, ncol=3)
rownames(d3) <- c("C","A","B")
colnames(d3) <- c("C", "A","B")

This creates two related matrices. Lets pretend that d1 contains info on how far apart different strains of a species (e.g. A, B, C) where isolated from one another, while d3 contains a pairwise genetic difference between these same isolates. I need these two matrices to be in the same order to perform the mantel test.

When I try using order, I loose the matrix:

d3[order(rownames(d3))]
[1] 0.2 0.3 0.0

d3[order(as.data.frame(rownames(d3)))]
[1] 0.2 0.3 0.0

Upvotes: 1

Views: 1158

Answers (1)

ONeillMB1
ONeillMB1

Reputation: 343

As Richard points out, I was missing a comma.

d3[order(rownames(d3)), order(colnames(d3))]

does exactly what I want!

Upvotes: 1

Related Questions