0

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

2
  • 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
    Apr 20, 2016 at 15:57
  • just wrote the example in the main question
    – fcid
    Apr 20, 2016 at 16:03

1 Answer 1

1

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
1
  • Thanks! This is what I wanted :)
    – fcid
    Apr 20, 2016 at 16:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.