点矩阵之间的距离,简单的 if 和 for

Distance between a matrix of points, simple if & for's

我想要 运行 一个给出两点之间距离的函数。我想计算所有点之间的距离我该怎么做。我知道可以使用 iffor 来完成,但我不太擅长使用这些。

我的函数是:

Distance<- function(x,y)    {
  round(sqrt(sum((x - y) ^ 2)),3)
}

我在上述函数的东向和北向或 x 和 y 中有 34 个点:

easting=rbind(609027, 609282, 609501,609497,609405,609704,609718,610277,610530,610573,609875,608947,609865,611105,611169,611243,611388,611598,611339,611310,611212,611150,611358,611626,611763,611887,612043,612134,612160,612539,612857,613062,613154,613303)
northing=rbind(1534293,1534470,1534630,1534848,1534027,1535054,1535315,1535583,1535717,1536254,1536351,1536700,1536746,1536762,1537003,1537261,1537489,1537685,1537838,1538103,1538500,1538812,1539217,1539342,1539627,1539842,1540027,1540357,1540628,1540911,1541623,1541896,1542117,1542494)

如果coords<-as.data.frame(easting,northing)是我的数据集,那么我想计算coords[i,]coords[j,]之间的距离。其中 ij 是数据集中的行。

谢谢

首先,您需要更改一些有关如何创建 data.frame 的细节。不要使用 cbind 定义向量 eastingnorthing,而是使用 c。然后使用 data.frame,而不是 as.data.frame.

easting = c(609027, 609282, 609501,609497,609405,609704,609718,610277,610530,610573,609875,608947,609865,611105,611169,611243,611388,611598,611339,611310,611212,611150,611358,611626,611763,611887,612043,612134,612160,612539,612857,613062,613154,613303)
northing = c(1534293,1534470,1534630,1534848,1534027,1535054,1535315,1535583,1535717,1536254,1536351,1536700,1536746,1536762,1537003,1537261,1537489,1537685,1537838,1538103,1538500,1538812,1539217,1539342,1539627,1539842,1540027,1540357,1540628,1540911,1541623,1541896,1542117,1542494)
coords <- data.frame(easting, northing)

现在,为了使用函数 apply,您还需要更改您的函数,让它接受一个向量作为参数。

Distance<- function(x, y)    {
  round(sqrt(sum((x - y) ^ 2)),3)
}

并使用嵌套 for 循环

d <- numeric(34^2)
k <- 0
for(i in seq_len(nrow(coords)))
    for(j in seq_len(nrow(coords))){
        k <- k + 1
        d[k] <- Distance(coords[i, ], coords[j, ])
    }

您可以使用 dist 函数:

df  <- data.frame(easting=easting,northing = northing)
dist(df) # or round(dist(df,upper=T,diag=T),3)

前三行示例:

round(dist(df[1:3,], upper=T,diag=T),3)

        1       2       3
1   0.000 310.409 581.588
2 310.409   0.000 271.221
3 581.588 271.221   0.000

比较:

round(dist(df[1:3,]),3)

        1       2
2 310.409        
3 581.588 271.221