I understand there are several tools out there that can help me accomplish my goal, but I think I'm running into more of a conceptual roadblock. I've tried to implement a fully reproducible example in seeking assistance.

The situation: I have two point shapefiles, one with 5 points (fewpoints.shp) and the other with many points ~100 (manypoints.shp). For each of the many points, I'd like to find the distance to each of the 5 points, such that the final df looks like:

ID DistPnt1 DistPnt2 DistPnt3 DistPnt4 DistPnt5 1 2 3 ... 100

I've been able to generate a distance matrix and melt it into a dataframe, but I'm having trouble understanding how I'm supposed to retain the original ids such that I can merge them back onto manypoints.shp.

Reproducible example:


MN <- us_states(resolution="low", states = "MN")


MNspdf <- as_Spatial(MN)

smallpoints <-spsample(MNspdf , 5, type = "random")

manypoints <-spsample(MNspdf , 100, type = "random")

spDists(manypoints, smallpoints)

Is it safe to assume that each row corresponds to the original rows of the manypoints.shp? Am I missing something?


It doesn't seem to be explicitly stated that, if:

d = spDists(a,b)

then d[i,j] is the distance of a[i] to b[j]:

 ‘spDists’ returns a full matrix of distances in the metric of the
 points if longlat=FALSE, or in kilometers if longlat=TRUE; 

but any alternative ordering would be so bizarre as to be worth mentioning. I would safely assume the returned distance matrix is so ordered.

If it worries you, contact the author and ask for clarification and an explicit statement in the documentation for the next version.

  • to my rescue yet again. I manually checked a few and they seem to be aligning properly. Might make a quick comment on the repo to confirm...also trying to get better at starting with the reproducible example rather than promising them but never delivering!
    – user128912
    Nov 9 '19 at 14:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy