Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract the lower triangle of a Distance matrix into pairwise columns values in R

Tags:

r

I have a distance matrix called mydist. I want to extract the lower triangle of the matrix into pairwise combination of column values. For example:

sampleA          sampleB              values
S05-F13-P01_C   S05-F13-P01_C         2251
S08-F10-P01_C   S08-F10-P01_C         2246

. . so on

Data

mydist<-structure(c("2251", "1923", "2085", "1954", "2105", "0", "2246", 
"2094", "1955", "2127", "0", "0", "2521", "2110", "2329", "0", 
"0", "0", "2276", "2141", "0", "0", "0", "0", "2561"), .Dim = c(5L, 
5L), .Dimnames = list(c("S05-F13-P01_C", "S08-F10-P01_C", "S08-F11-P01_C", 
"S09-F66-P01_C", "S09-F67-P01_C"), c("S05-F13-P01_C", "S08-F10-P01_C", 
"S08-F11-P01_C", "S09-F66-P01_C", "S09-F67-P01_C")))
like image 514
MAPK Avatar asked Nov 16 '25 12:11

MAPK


2 Answers

We can try

i1 <- lower.tri(mydist, diag=TRUE)
i2 <- which(i1, arr.ind=TRUE)
data.frame(sampleA = colnames(mydist)[i2[,1]], 
        sampleB = colnames(mydist)[i2[,2]], value = mydist[i1])
like image 98
akrun Avatar answered Nov 19 '25 08:11

akrun


I would consider the following:

data.frame(as.table(mydist))[lower.tri(mydist, diag = TRUE), ]
##             Var1          Var2 Freq
## 1  S05-F13-P01_C S05-F13-P01_C 2251
## 2  S08-F10-P01_C S05-F13-P01_C 1923
## 3  S08-F11-P01_C S05-F13-P01_C 2085
## 4  S09-F66-P01_C S05-F13-P01_C 1954
## 5  S09-F67-P01_C S05-F13-P01_C 2105
## 7  S08-F10-P01_C S08-F10-P01_C 2246
## 8  S08-F11-P01_C S08-F10-P01_C 2094
## 9  S09-F66-P01_C S08-F10-P01_C 1955
## 10 S09-F67-P01_C S08-F10-P01_C 2127
## 13 S08-F11-P01_C S08-F11-P01_C 2521
## 14 S09-F66-P01_C S08-F11-P01_C 2110
## 15 S09-F67-P01_C S08-F11-P01_C 2329
## 19 S09-F66-P01_C S09-F66-P01_C 2276
## 20 S09-F67-P01_C S09-F66-P01_C 2141
## 25 S09-F67-P01_C S09-F67-P01_C 2561
like image 27
A5C1D2H2I1M1N2O1R2T1 Avatar answered Nov 19 '25 06:11

A5C1D2H2I1M1N2O1R2T1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!