Reputation: 672
I am trying to calculate the distance between all possible pairs of coordinates in a list of coordinates. However, I am surprisingly getting NaN for some pairs of coordinates that you should definitely be able to calculate the distance between.
My coordinates are in decimal longitude and latitude. I am using the distHaversine function from the geodist package in R.
Here is a sample of a pair of coordinates for which distHaversine returns NaN. I tried this code with many other pairs of coordinates and it works correctly.
# Create long, lat matrix with two sets of coordinates
coord_list <- matrix(c(2.5, -177.5, 5.5, -5.5), ncol=2)
coord_list
# Create a matrix with the distance between each pair of points (zero on the diagonals)
dist <- apply(coord_list, 1,
FUN=function(X) {
distHaversine(X, coord_list)
})
dist
# [,1] [,2]
#[1,] 0 NaN
#[2,] NaN 0
In case it's relevant, I need these distances for an inverse distance weighting matrix for spatially weighted regressions. However, I'd rather figure out why distHaversine is occasionally returning NaN than calculate the matrix differently (which I know how to do).
Thanks for your help!
Upvotes: 1
Views: 758
Reputation: 47156
Thanks for reporting. This was fixed in geosphere 1.5-7.
I would use the very precise geosphere::distGeo
function in stead of geopshere::distHaversine
(which is more for historical interest)
To get the distance for all points to all points, you can use the distm
function
coords <- matrix(c(2.5, -177.5, 5.5, -5.5, 0, 0), ncol=2)
library(geosphere)
distm(coords)
# [,1] [,2] [,3]
#[1,] 0.0 19395754 693590.1
#[2,] 19395754.2 0 19703549.9
#[3,] 693590.1 19703550 0.0
Or the pointDistance
function in the raster
package (and the same algorithm as distGeo
):
library(raster)
pointDistance(coords, lonlat=TRUE)
# [,1] [,2] [,3]
#[1,] 0.0 NA NA
#[2,] 19395754.2 0 NA
#[3,] 693590.1 19703550 0
Upvotes: 0