I want to know the fastest algorithms for obtaining the cartesian distances between each point in a SpatialPointsDataFrame (X
) and either (a) the closest point in a second SpatialPointsDataFrame (Y
), or (b) the closest line segment in a SpatialLinesDataFrame (Y
). So this is basically 2 questions, with perhaps the same answer.
For the lines, I know I can use dist2Line(X,Y, distfun=distGeo)
but this is insanely slow. I also tried using nncross
, after converting both X
and Y
to ppp objects, as below. This is did NOT work; heat mapping the new distance measure showed that it does not radiate from Y
.
X_ppp <- as(X, "ppp")
Y_psp <- as(Y, "psp")
distR <- nncross(X_ppp,Y_ppp,what="dist",k=1)
X$dist2road <- distR
For lines, I also tried using gDistance(X,Y)
but was met with the error, for i=1,2: Spatial object i is not projected; GEOS expects planar coordinates
. I think this is because I'm using lat-lon, and it needs a true projection. But all the files i'm working with are lat-lon, and I'm not sure how to choose and specify a projection (for tanzania) w/out coping it from another file.
For points, again using the nncross
approach resulted in definitely wrong distances. (In each the point and line case, is this because the output vector is not ordered in the same way that the points within X are? If so, I see now way of outputting an ID for the point within X.)
Also for points, this knn
code below did work. But it's clearly not in cartesian distance, and so I'd like to convert it or find some other algorithm that provides cartesian distance.
knn.results = knn(data=coordinates(market.shp),
query=coordinates(tzprice.shp), k=1)
knn.results <- data.frame(knn.results)
tzprice.shp$dist2market <- knn.results[,2]
Basically, my hope is to find the fastest algorithm for each purpose (distance to nearest point, distance to nearest line), with output either in cartesian distance or convertible to cartesian distance. Thanks!
SpatialPolygonsDataFrame
, and the same approach should work equally well with aSpatialLinesDataFrame
. – Mendacious