说我有
> 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
如何从索引4
返回到行号和列号(5,1)
?
答案 0 :(得分:6)
可能有一个更整洁的方式......
dist.x <- dist(x)
which(as.matrix(dist.x) == max(dist.x) & lower.tri(dist.x), arr.ind=TRUE)
# row col
# 5 5 1
答案 1 :(得分:2)
dist有一个as.matrix方法,它很有用。你可以试试这个:
kk <- as.matrix(dist(x))
which(kk == max(kk), arr.ind=TRUE)
对于您的示例,
row col
5 5 1
1 1 5
答案 2 :(得分:1)
dist
返回类“dist”的对象。您应该首先阅读帮助文件,其中包含:
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.
发布的其他答案会以有用的方式修改“dist”对象。