[英]Calculate distance between two long lat coordinates in a dataframe
I want to calculate the distance between several GPS points. 我想计算几个GPS点之间的距离。 I tried 我试过了
distm(c(lon1,lat1), c(lon2,lat2), fun = distHaversine)
which worked for one point, but not for the columns in my data frame. 这只适用于一点,但不适用于我的数据框中的列。
So I tried as recommended here: 所以我按照这里的建议尝试了:
Calculate distance between 2 lat longs 计算两个纬度之间的距离
But I do get different results for these two calculations: 但是对于这两种计算,我确实得到了不同的结果:
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
So how can I calculate the correct distances (which is distm(c(lon1,lat1), c(lon2,lat2), fun = distHaversine)) between two GPS points in the columns of my data frame? 那么,如何计算数据帧列中两个GPS点之间的正确距离(即distm(c(lon1,lat1),c(lon2,lat2),fun = distHaversine))? I double-checked with so distances that I know I get the right distances this way. 我仔细检查了一下距离,以至于我知道以这种方式得到了正确的距离。
Thanks in advance. 提前致谢。
Given that the output you want to store in the new column is this: 鉴于您要存储在新列中的输出是这样的:
77.54033 135.23165
Try this 尝试这个
df$distance<-distHaversine(df[,1:2], df[,3:4])
Which should return 哪个应该返回
> 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
What exactly is the question? 到底是什么问题? Don't you already have all the distances you need with distHaversine()
? 您不是已经拥有distHaversine()
所需的所有距离了吗?
Do you want to add the distance as column in the dataframe? 是否要将距离添加为数据框中的列? Here you go: 干得好:
f$dist <- distm(x = df[, c('lon1', 'lat1')],
y = df[, c('lon2', 'lat2')],
fun = distHaversine
)
I found another solution for the problem 我找到了解决该问题的另一种方法
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.