我想运行一个给出两点之间距离的函数。我想计算所有点之间的距离,我该怎么做。我知道可以使用if
或for
来完成,但我使用它们并不是很好。
我的功能是:
Distance<- function(x,y) {
round(sqrt(sum((x - y) ^ 2)),3)
}
我在东部和北部或x&amp;以上功能:
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,]
之间的距离。其中i
,j
是数据集中的行。
由于
答案 0 :(得分:2)
首先,您需要更改有关如何创建data.frame
的详细信息。不要使用easting
定义向量northing
和cbind
,而是使用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, ])
}
答案 1 :(得分:2)
您可以使用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