I am trying to find the k-nearest neighbor on a sphere using R.
As I deal with million of points brute force is not an option.
Does anyone know how I could do? Thank you
I am trying to find the k-nearest neighbor on a sphere using R.
As I deal with million of points brute force is not an option.
Does anyone know how I could do? Thank you
Using the link provided by Ben Bolker I manage to solve my pb.
lonlat2xyz=function (lon, lat, r)
{
lon = lon * pi/180
lat = lat * pi/180
if (missing(r))
r <- 6378.1
x <- r * cos(lat) * cos(lon)
y <- r * cos(lat) * sin(lon)
z <- r * sin(lat)
return(cbind(x, y, z))
}
lon1=runif(100,-180,180);lon2=runif(100,-180,180);lat1=runif(100,-90,90);lat2=runif(100,-90,90)
xyz1=lonlat2xyz(lon1,lat1)
xyz2=lonlat2xyz(lon2,lat2)
library(nabor)
out=knn(data=xyz1,query = xyz2,k=20)
library(maps)
map()
points(lon1,lat1,pch=16,col="black")
points(lon2[1],lat2[1],pch=16,col="red")
points(lon1[out$nn.idx[1,]],lat1[out$nn.idx[1,]],pch=16,col="blue")
Note the distances given by knn function are NOT the geographical distances !