0

I have a matrix object that looks like the matrix below. It is a distance matrix between localities, but I need to sort them according to another order, something like CLR, LAG, CDA, ANT, CLC. I read some solutions with plyr with they didn't work in my case.

    ANT     CDA     CLC     CLR     LAGM
ANT 0.00    6.45    9.25    6.76    5.41
CDA 6.45    0.00    6.32    4.65    5.31
CLC 9.25    6.32    0.00    6.93    5.91
CLR 6.76    4.65    6.93    0.00    6.76
LAG 5.41    5.31    5.91    6.76    0.00

desired output (with the correct distances)

     CLR    LAGM    CDA ANT CLC
CLR                 
LAG                 
CDA                 
ANT                 
CLC                 
Andrés Parada
  • 270
  • 5
  • 19

2 Answers2

1

You can do:

m <- read.table(text=
'    ANT     CDA     CLC     CLR     LAG
ANT 0.00    6.45    9.25    6.76    5.41
CDA 6.45    0.00    6.32    4.65    5.31
CLC 9.25    6.32    0.00    6.93    5.91
CLR 6.76    4.65    6.93    0.00    6.76
LAG 5.41    5.31    5.91    6.76    0.00')
m <- as.matrix(m)

my.o <- c("CLR", "LAG", "CDA", "ANT", "CLC")
m[my.o, my.o]
#      CLR  LAG  CDA  ANT  CLC
# CLR 0.00 6.76 4.65 6.76 6.93
# LAG 6.76 0.00 5.31 5.41 5.91
# CDA 4.65 5.31 0.00 6.45 6.32
# ANT 6.76 5.41 6.45 0.00 9.25
# CLC 6.93 5.91 6.32 9.25 0.00

You can do it also with integer indices:

my.o <- c(4,5,2,1,3)
m[my.o, my.o]

In the case of differences between rownames and columnames of your matrix you can calculate the integer indices:

my.o <- c("CLR", "LAG", "CDA", "ANT", "CLC")
ind <- match(my.o, rownames(m))
m[ind, ind]
jogo
  • 12,306
  • 11
  • 34
  • 41
0

I would convert my matrix into a dataframe before applying any processing. Sort then becomes a straightforward order function in a dataframe. Anyway sorting a matrix is not a good idea IMHO.

Consider this example, and see if you can make out how I have used a sample matrix and sorted on 2 of its columns and listed only 5 columns. You can modify to as many columns you want.

> mat<-matrix(sample(100),nrow=10,ncol=10)
> mat
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]   36    7   96   65   54   33   95   53   72    67
 [2,]   94   45   66   39   46    9   28   10   84   100
 [3,]   16   44   58   88    6   12   75   59   74    85
 [4,]   97   86   69   64   57   13   78   83   26    63
 [5,]    5   27   23   35   42   19   81    2   52    48
 [6,]   11   91   22   90   77   89   71   31   50    43
 [7,]   25   56   14   40   61   41   99   18   98    21
 [8,]   55   30   62   38   92    3   37    8   68     1
 [9,]   80   29   34   79   24   17   15   76   70    60
[10,]    4   93   47   87   49   73   20   82   32    51

>  x<-as.data.frame(mat)
>  x[,c(1:5)][order(x$V3,x$V5),]
   V1 V2 V3 V4 V5
7  25 56 14 40 61
6  11 91 22 90 77
5   5 27 23 35 42
9  80 29 34 79 24
10  4 93 47 87 49
3  16 44 58 88  6
8  55 30 62 38 92
2  94 45 66 39 46
4  97 86 69 64 57
1  36  7 96 65 54
Lazarus Thurston
  • 1,020
  • 13
  • 28