Calculate distance between two long lat coordinates in a dataframe

旧城冷巷雨未停 提交于 2019-12-04 17:13:38

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()?

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")
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!