3

说我有

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

4

3 回答 3

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
于 2013-06-19T12:55:29.500 回答
2

dist 有一个 as.matrix 方法很有用。你可以试试这个:

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

对于你的例子,

  row col
5   5   1
1   1   5
于 2013-06-19T12:59:58.480 回答
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”对象。

于 2013-06-19T12:56:48.640 回答