说我有
> 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)
?
说我有
> 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)
?
可能有更整洁的方式...
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 有一个 as.matrix 方法很有用。你可以试试这个:
kk <- as.matrix(dist(x))
which(kk == max(kk), arr.ind=TRUE)
对于你的例子,
row col
5 5 1
1 1 5
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”对象。