如何根据两个坐标之间的最近距离对矩阵进行排序?
例如,我有这个矩阵:
> x
[,1] [,2]
[1,] 1 1
[2,] 3 9
[3,] 2 6
[4,] 2 8
我希望矩阵的第一行有点是初始坐标。在两个坐标之间手动计算距离后,我发现x[1,]
与x[3,]
的距离最近。然后,x[3,]
与x[4,]
的距离最近。 x[4,]
与x[2,]
的距离最近。所以排序的矩阵将是:
[,1] [,2]
[1,] 1 1
[2,] 2 6
[3,] 2 8
[4,] 3 9
我试着写下面的R代码。但它没有用。
closest.pair <- c(NA,NA)
closest.distance <- Inf
for (i in 1:(n-1))
for (j in (i+1):n) {
dist <- sum((houses[i,]-houses[j,])^2)
if (dist<closest.distance) {
closest.pair <- c(i,j)
}
print(houses[closest.pair,])
}
答案 0 :(得分:0)
以下是使用循环的可能解决方案:
## We determine the minimum distance between the coordinates at the current index cur
## and those at the remaining indexes ind
cur = 1;
ind = c(2:nrow(x));
## We put our resulting sorted indexes in sorted
sorted = 1;
while(length(ind)>=2){
pos = ind[which.min(rowSums((x[cur,]-x[ind,])^2))];
## At each iteration we remove the newly identified pos from the indexes in ind
## and consider it as the new current position to look at
ind = setdiff(ind,pos);
cur = pos;
sorted = c(sorted,pos)}
sorted = c(sorted,ind)
res = x[sorted,];
[,1] [,2]
[1,] 1 1
[2,] 2 6
[3,] 2 8
[4,] 3 9
答案 1 :(得分:0)
您可以使用for循环,如下所示:
D=`diag<-`(as.matrix(dist(x)),NA)# Create the distance matrix, and give the diagonals NA values.
然后运行for循环
x[c(i<-1,sapply(1:(nrow(x)-1),function(j)i<<-which.min(D[i,]))),]
[,1] [,2]
[1,] 1 1
[2,] 2 6
[3,] 2 8
[4,] 3 9
这个for循环可能看起来很奇怪!看一看:
m=c()
i=1
for(j in 1:(nrow(x)-1)){
i= which.min(D[i,])
m=c(m,i)
}
x[c(1,m),]
[,1] [,2]
[1,] 1 1
[2,] 2 6
[3,] 2 8
[4,] 3 9
您也可以使用Reduce
x[Reduce(function(i,j)which.min(D[,i]),1:(nrow(x)-1),1,,T),]
[,1] [,2]
[1,] 1 1
[2,] 2 6
[3,] 2 8
[4,] 3 9