I followed the post Finding euclidean distance in R{spatstat} between points, confined by an irregular polygon window to the end and made it all work, great. In my case however I want to get the distance points in data A to points in data B but only if both data sets have the same ID value. My issue can follow the example in Finding euclidean distance in R{spatstat} between points, confined by an irregular polygon window but with two Pts data frames and instead of finding the distance between the points in Pts I want to find the distance between points in Pts1 and Pts2 if Pts1$ID == Pts2$ID (assuming you add and ID column). There are many levels of ID in both Pts1 and Pts2.
1 Answers
Disclaimer: This is written without testing any of the code, so there is no guarantee that it works, but it gives a straight forward way of approaching the problem.
The function gdistance::costDistance
accepts a third argument to specify distance from the points in the second argument to the points in the third argument, so having data A and data B should pose no problem.
Now for doing it for each ID: What about simply splitting the point sets into separate ones for each ID and then execute the distance code for each of these in a for loop?
If A
and B
are data.frames
with your coordinates and IDA
and IDB
are factors with same levels indicating the IDs of the points then you can split into lists and calculate distance like this (assuming you have run the appropriate code from the answer you link to):
Alist <- split(A, IDA)
Blist <- split(B, IDB)
rslt <- list()
for(i in seq_along(Alist)){
rslt[[i]] <- costDistance(tr1, Alist[[i]], Blist[[i]])
}

- 4,347
- 1
- 10
- 18
-
This is useful but Alist and Blist need to be SpatialPoints() in order to run costDistance(). Maybe convert to SpatialPoints() before splitting? – wraymond Oct 16 '15 at 17:42
-
1I haven't tested this but the argument documentation says: fromCoords: first set of point locations (of ‘SpatialPoints’, matrix or numeric class) toCoords: second, optional set of point locations (of ‘SpatialPoints’, matrix or numeric class) – Ege Rubak Oct 17 '15 at 13:48
-
Yes you can set the to and form coords. However, then is computes 17 X 10000 distances when it only needs to compute distances between points that have the same identifier. – wraymond Nov 25 '15 at 00:24
-
The numbes 17 and 10000 mean nothing to me. I don't see them mentioned anywhere in your question. How would I know whether it is right or wrong to compute this number of distances? Are you doing this with the splitted lists of data in a for loop? Can you share some example code so we can see exactly what you are doing? – Ege Rubak Nov 26 '15 at 00:42