r - 根据两个坐标之间的最近距离对矩阵进行排序

标签 r matrix distance

如何根据两个坐标之间的最近距离对矩阵进行排序?

例如,我有这个矩阵:

> 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,])
  }

最佳答案

这是一个使用循环的可能解决方案:

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

关于r - 根据两个坐标之间的最近距离对矩阵进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48142562/

相关文章:

c++ - 在 C++ 中对大输入实现矩阵的最有效方法?

css - 使用 css/jsf-2 的文本元素的相同距离

php - 如何在纯 PHP 中返回半径内的坐标? (没有MySQL)

r - 代入R中句子第N个词的模式

c++ - 在另一个坐标系中查找点的坐标

numpy - 给定两个向量,得到一个 bool 值矩阵,指示向量元素在何处相等

iPhone:使用 GPS 计算步行距离

r - 使用 sjPlot 更改plot_model中的变量标签以获得随机效应

r - 从 R 中的数据帧创建成对值的方阵

r - 有没有办法不将 `by` 列作为 data.table 分组中的第一列返回