0
votes

I have a series of elements A, B, C and D. For each possible pair (AB, AC, AD, BC, BD, CD), I have computed a distance measure and store in a vector at position x.

Position x is determined by the following loop: (n is number of elements, in this example case, 4)

 n=1
 for i in 1:(n-1)
     for j in (i+1):n
         distancevector[n] = distancemeasure
         n = n+1

What is the easiest way to transform distancevector into a distance matrix in R?

Example:

distancevector = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6)

what I want would be this distance matrix:

A 1 0.1 0.2 0.3

B 0.1 1 0.4 0.5

C 0.2 0.4 1 0.6

D 0.3 0.5 0.6 1

1
Could you provide an example? A way could be to cheat with the "dist" class that has a as.matrix method. I.e. assuming a distance vector vec = runif(6) see as.matrix(structure(vec, class = "dist", Size = 4))alexis_laz
just wrote the example in the main questionfcid

1 Answers

1
votes

In base R we can try:

n <- 4
distancevector <- c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6)

D <- diag(n)
D[lower.tri(D)] <- distancevector
D[upper.tri(D)] <- t(D)[upper.tri(D)]

> D
     [,1] [,2] [,3] [,4]
[1,]  1.0  0.1  0.2  0.3
[2,]  0.1  1.0  0.4  0.5
[3,]  0.2  0.4  1.0  0.6
[4,]  0.3  0.5  0.6  1.0