R 点矩阵之间的距离,简单if&;对于';s
我想运行一个函数,给出两点之间的距离。我想计算所有点之间的距离,如何计算。我知道可以使用R 点矩阵之间的距离,简单if&;对于';s,r,matrix,geometry,distance,R,Matrix,Geometry,Distance,我想运行一个函数,给出两点之间的距离。我想计算所有点之间的距离,如何计算。我知道可以使用if或for来完成,但我不擅长使用这些 我的职能是: Distance<- function(x,y) { round(sqrt(sum((x - y) ^ 2)),3) } 如果coords首先,您需要更改创建data.frame的一些细节。使用c代替使用cbind定义向量easting和northing。然后使用data.frame,而不是作为.data.frame easting =
if
或for
来完成,但我不擅长使用这些
我的职能是:
Distance<- function(x,y) {
round(sqrt(sum((x - y) ^ 2)),3)
}
如果
coords首先,您需要更改创建data.frame
的一些细节。使用c
代替使用cbind
定义向量easting
和northing
。然后使用data.frame
,而不是作为.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)
并对
循环使用嵌套的
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, ])
}
d您可以使用以下功能:
df <- data.frame(easting=easting,northing = northing)
dist(df) # or round(dist(df,upper=T,diag=T),3)
比较:
round(dist(df[1:3,]),3)
1 2
2 310.409
3 581.588 271.221
这不是只计算34个距离而不是所有34^2个距离吗?也许可以使用expand.grid()
。无论如何——这些列只包含单个数字,而不包含点。@JohnColeman好的,现在我已经看到Florian的答案了。我将编辑我的。问题仍然是,您实际上是在计算某些点的x
坐标和其他点的y
坐标之间的绝对值,而不是计算点之间的距离<代码>东距
是x坐标,北距
是y坐标。计算northing
元素和easting
元素之间的距离实际上没有意义。当然,使用内置的dist
会更有效率,但您指出OP如何构建其数据帧的问题是完全正确的。如果我使用全部34行,这将为我提供561个值。我应该得到1156。从每一行,你可以测量到其他33行的距离<代码>561=(34*33)/2
。这就是唯一距离的总和。如果您使用`round(dist(df,upper=T,diag=T),3)
而不是dist(df)
,您还将获得对角线和上方三角形上的值。希望澄清一下。你是说其余的值都省略了?它是我在结果中看到的空白。如果使用<代码> DIST(DF),其余的值将被省略。如果使用round(dist(df[1:3,],upper=T,diag=T),3)
,则构建全距离矩阵。请查看我的更新答案。谢谢,如果我使用纬度和经度而不是东距和北距,那么为什么这些值与geosphere::distm
的值略有不同。这可能是投影错误吗?
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