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)
?
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
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
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.