How to use distHaversine function?

倾然丶 夕夏残阳落幕 提交于 2019-12-22 12:39:42

问题


I am trying to use the distHavrsine function in R, inside a loop to calculate the distance between some latitude and longitude coordinates for a several hundred rows. In my loop I have this code:

if ((distHaversine(c(file[i,"long"], file[i,"lat"]),
                   c(file[j,"long"], file[j,"lat"]))) < 50 )

after which if the distance is less than 50 meters i want it to record those rows, and where the latitude and longitude coordinates it is referencing look like:

0.492399367 30.42530045

and

0.496899361 30.42497045

but i get this error

Error in .pointsToMatrix(p1) : latitude > 90


回答1:


i get this error "Error in .pointsToMatrix(p1) : latitude > 90". Can anyone explain why and how to solve?

The error tells you that you got latitude values greater than 90, which is out of scope:

library(geosphere)
distHaversine(c(4,52), c(13,52))
# [1] 616422
distHaversine(c(4,52), c(1,91))
# Error in .pointsToMatrix(p2) : latitude > 90

You can solve this issue by only feeding distHaversine with coordinates inside the accepted ranges.

I am trying to use the distHavrsine function in R, inside a loop to calculate the distance between some latitude and longitude coordinates for a several hundred rows. (...) if the distance is less than 50 meters i want it to record those rows

Have a look at the distm function, which calculates a distance matrix for your few hundred rows easily (i.e. without loops). It uses distHaversine by default. For example, to get the data frame rows that are closer then 650000 meters:

df <- read.table(sep=",", col.names=c("lon", "lat"), text="
4,52
13,52 
116,39")
(d <- distm(df))
#         [,1]    [,2]    [,3]
# [1,]       0  616422 7963562
# [2,]  616422       0 7475370
# [3,] 7963562 7475370       0

d[upper.tri(d, T)] <- NA
( idx <- which(d < 650000, arr.ind = T) )
#      row col
# [1,]   2   1
cbind(df[idx[, 1], ], df[idx[, 2], ])
#   lon lat lon lat
# 2  13  52   4  52


来源:https://stackoverflow.com/questions/36110815/how-to-use-disthaversine-function

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