1

Given a matrix of distances between points in one dimension, I'd like to use R to convert the matrix into an ordered vector of points from left to right (or right to left, doesn't matter) as well as outputting a vector of distances from the first element of that vector to all subsequent elements.

For example, this matrix:

> m2
   A  B C D
A  0 11 2 6
B 11  0 9 5
C  2  9 0 4
D  6  5 4 0

...represents the following relationship:

 2   4    5
A--C----D-----B

And I'd like to output the vectors

X = c(A, C, D, B) (or c(B, D, C, A))
Y = c(2, 4, 5) (or c(5, 4, 2)

I would be grateful for any help with this.

Sigurgeir
  • 365
  • 2
  • 12
  • Have you looked at the materials for working with neighbor relations in the `igraph` package? https://stackoverflow.com/q/21300821/3362993 – jsta Feb 10 '19 at 15:03
  • I have not. I felt sure there must be a library for doing this but I'm struggling to find the appropriate search terms (distance matrix etc sort of describes other things). Any particular function in igraph that you have in mind? – Sigurgeir Feb 10 '19 at 15:10

1 Answers1

1

We may use multidimensional scaling with one dimension:

(z <- sort(cmdscale(m, k = 1)[, 1]))
#     B     D     C     A 
# -6.25 -1.25  2.75  4.75 

So,

(A <- names(z))
# [1] "B" "D" "C" "A"
(B <- unname(diff(z)))
# [1] 5 4 2
Julius Vainora
  • 47,421
  • 9
  • 90
  • 102