r - sorting the output of dist() -


i have matrix m

m <- matrix (    c( 2, 1, 8, 5,      7, 6, 3, 4,      9, 3, 2, 8,      1, 3, 7, 4),   nrow  = 4,   ncol  = 4,   byrow = true)  rownames(m) <- c('a', 'b', 'c', 'd') 

now, i'd order rows of m based on respective distance, use dist()

dist_m <- dist(m) 

dist_m is, when printed

                  b         c b  8.717798 c  9.899495  5.477226 d  2.645751  7.810250 10.246951 

since want ordered, try sort(dist_m) prints

[1]  2.645751  5.477226  7.810250  8.717798  9.899495 10.246951 

which want. i'd more happy if printed names of 2 rows of number distance, like

 2.645751   d  5.477226  b  c  7.810250  b  d  8.717798   b  9.899495   c 10.246951  c  d 

this possible, have no idea how achieve this.

one option convert dist matrix, replace upper triangle values 0, melt, subset non-zero values, , order based on 'value' column.

m1 <- as.matrix(dist_m) m1[upper.tri(m1)] <- 0 library(reshape2) m2 <- subset(melt(m1), value!=0) m2[order(m2$value),3:1] #         value var2 var1 #4   2.645751       d #7   5.477226    b    c #8   7.810250    b    d #2   8.717798       b #3   9.899495       c #12 10.246951    c    d 

or base r option suggested @david arenburg after getting 'm1'

 m2 <- cbind(which(m1!=0, arr.ind=true), value= m1[m1!=0])  m2[order(m2[,'value']),] 

Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

Nuget pack csproj using nuspec -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -