3

Say I have

> x<-1:5
> dist(x)
  1 2 3 4
2 1      
3 2 1    
4 3 2 1  
5 4 3 2 1
> which(dist(x)==max(dist(x)))
[1] 4

How do I get from the index 4 back to the row and column numbers (5,1)?

TooTone
  • 7,129
  • 5
  • 34
  • 60

3 Answers3

6

There might be a tidier way ...

dist.x <- dist(x)
which(as.matrix(dist.x) == max(dist.x) & lower.tri(dist.x), arr.ind=TRUE)
#   row col
# 5   5   1
Matthew Plourde
  • 43,932
  • 7
  • 96
  • 113
2

dist has a method to as.matrix which is useful. You can try this:

kk <- as.matrix(dist(x))
which(kk == max(kk), arr.ind=TRUE)

For your example,

  row col
5   5   1
1   1   5
asb
  • 4,392
  • 1
  • 20
  • 30
  • Matthew has already given this *exact* answer above (as had I, but I deleted mine because it was duplicate info and he answered first). – Simon O'Hanlon Jun 19 '13 at 13:05
1

dist returns an object of class "dist." You should start by reading the help file, which says:

Value

dist returns an object of class "dist".

The lower triangle of the distance matrix stored by columns in a vector, say do. If n is the number of observations, i.e., n <- attr(do, "Size"), then for i < j ≤ n, the dissimilarity between (row) i and j is do[n*(i-1) - i*(i-1)/2 + j-i]. The length of the vector is n*(n-1)/2, i.e., of order n^2.

The other answers posted modify the "dist" object in useful ways for you.

Carl Witthoft
  • 20,573
  • 9
  • 43
  • 73