Albert Vilella
2006-Jun-13 11:45 UTC
[R] sorting matrix elements by given rownames and colnames
Hi all, I would like to know if it is possible to sort the columns and rows in a matrix given a specified order of their colnames and rownames. For example: I would like the original matrix: RNO FRU ANG CEL DAR PTR RNO 3.45 1.35 2.16 2.25 1.43 1.20 FRU 1.31 Inf 2.22 2.36 1.34 1.40 ANG 1.30 1.30 11.61 1.37 1.33 1.35 CEL 1.34 1.35 1.37 Inf 1.37 1.40 DAR 1.40 1.29 2.29 2.39 9.62 1.48 PTR 1.08 1.30 2.06 2.17 1.39 8.17 To be sorted in a top/down and left/right way in this order instead: "FRU","ANG","CEL","PTR","RNO","DAR". Thanks in advance, Albert.
Chuck Cleland
2006-Jun-13 11:54 UTC
[R] sorting matrix elements by given rownames and colnames
Albert Vilella wrote:> Hi all, > > I would like to know if it is possible to sort the columns and rows in > a matrix given a specified order of their colnames and rownames. For > example: > > I would like the original matrix: > > RNO FRU ANG CEL DAR PTR > RNO 3.45 1.35 2.16 2.25 1.43 1.20 > FRU 1.31 Inf 2.22 2.36 1.34 1.40 > ANG 1.30 1.30 11.61 1.37 1.33 1.35 > CEL 1.34 1.35 1.37 Inf 1.37 1.40 > DAR 1.40 1.29 2.29 2.39 9.62 1.48 > PTR 1.08 1.30 2.06 2.17 1.39 8.17 > > To be sorted in a top/down and left/right way in this order > instead: "FRU","ANG","CEL","PTR","RNO","DAR".X <- round(matrix(rnorm(36), ncol=6), 2) colnames(X) <- c("RNO", "FRU", "ANG", "CEL", "DAR", "PTR") rownames(X) <- c("RNO", "FRU", "ANG", "CEL", "DAR", "PTR") myord <- c("FRU", "ANG", "CEL", "PTR", "RNO", "DAR") X RNO FRU ANG CEL DAR PTR RNO -0.99 0.03 -0.78 -0.55 0.01 -0.64 FRU -0.50 -0.67 2.05 0.28 0.86 0.20 ANG -0.87 0.48 -0.26 0.00 -0.39 -0.18 CEL -0.71 0.55 1.32 0.36 -0.53 -0.53 DAR 0.92 -1.28 0.92 -0.19 0.56 -0.86 PTR -0.60 -0.95 -0.17 -1.23 0.41 -0.36 X[myord,myord] FRU ANG CEL PTR RNO DAR FRU -0.67 2.05 0.28 0.20 -0.50 0.86 ANG 0.48 -0.26 0.00 -0.18 -0.87 -0.39 CEL 0.55 1.32 0.36 -0.53 -0.71 -0.53 PTR -0.95 -0.17 -1.23 -0.36 -0.60 0.41 RNO 0.03 -0.78 -0.55 -0.64 -0.99 0.01 DAR -1.28 0.92 -0.19 -0.86 0.92 0.56> Thanks in advance, > > Albert. > > ______________________________________________ > R-help at stat.math.ethz.ch mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html-- Chuck Cleland, Ph.D. NDRI, Inc. 71 West 23rd Street, 8th floor New York, NY 10010 tel: (212) 845-4495 (Tu, Th) tel: (732) 512-0171 (M, W, F) fax: (917) 438-0894