我想计算几个GPS点之间的距离。 我试过了
distm(c(lon1,lat1), c(lon2,lat2), fun = distHaversine)
适用于一点,但不适用于数据框中的列。
所以我按照这里的推荐尝试了:
Calculate distance between 2 lat longs
但是我对这两个计算得到了不同的结果:
df <- read.table(sep=",", col.names=c("lat1", "lon1", "lat2", "lon2"),text="
7.348687,53.36575,7.348940,53.36507
7.348940, 53.36507,7.350939,53.36484")
# as recommended in the link above
distHaversine(df[,2:1], df[,4:3])
[1] 80.18433 223.97181
# with distm
distm(c(7.348687,53.36575), c(7.348940,53.36507), fun = distHaversine)
[,1]
[1,] 77.54033
distm(c(7.348940, 53.36507), c(7.350939,53.36484), fun = distHaversine)
[,1]
[1,] 135.2317
那么如何计算数据框列中两个GPS点之间的正确距离(dist(c(lon1,lat1),c(lon2,lat2),fun = distHaversine))?我仔细检查了距离,以至于我知道这种距离是正确的。
提前致谢。
答案 0 :(得分:3)
鉴于您要在新列中存储的输出是:
77.54033 135.23165
试试这个
df$distance<-distHaversine(df[,1:2], df[,3:4])
哪个应该返回
> df
lat1 lon1 lat2 lon2 distance
1 7.348687 53.36575 7.348940 53.36507 77.54033
2 7.348940 53.36507 7.350939 53.36484 135.23165
答案 1 :(得分:0)
究竟是什么问题?您是否已经拥有distHaversine()
所需的所有距离?
是否要将距离添加为数据框中的列?你走了:
f$dist <- distm(x = df[, c('lon1', 'lat1')],
y = df[, c('lon2', 'lat2')],
fun = distHaversine
)
答案 2 :(得分:0)
我找到了问题的另一种解决方案
for (i in 1:2) {
a<-df$lon1[i]
b<-df$lat1[i]
c<-df$lon2[i]
d<-df$lat2[i]
df$distance[i]<-distm(c(a,b),c(c,d), fun = distHaversine)
}
write.xlsx(df, file = "C:/Users/distances.xlsx")