I am attempting to match/link 2 datasets, each of which have a lat lon. I'd like to produce the closest n matches by distance for each given coordinate in the first dataset. I am able to get the closest match but not sure how to expand this to get n number of matches.
The datasets look like this- table_1
| id_1 | lat_1 | lon_ |
|---|---|---|
| a1 | 50.8613159 | 1.2483 |
| d7 | 50.8526967 | 1.2566349 |
| s2 | 50.8666 | 1.2433232 |
table_2
| id_2 | lat_2 | lon_2 |
|---|---|---|
| x2 | 50.8713562548622 | 1.24447448004003 |
| r1 | 50.8548464 | 1.2402125971721 |
| o9 | 50.87906755026 | 1.2453153747299 |
The code i've been using to determine the closest match has been finding the euclidean dist from the RANN package.
table_1[, c(3, 4)] <- as.data.frame(RANN::nn2(table_1[, c("lat_1", "lon_1")],
table_2[, c("lat_2", "lon_2")], k=1))
which returns an index number and distance. Ideally, i'd like my output to look like-
For 3 closest matches :
| id_1 | lat_1 | lon_1 | index_no |
|---|---|---|---|
| a1 | 50.8613159 | 1.2483 | 3 |
| a1 | 50.8613159 | 1.2483 | 2 |
| a1 | 50.8613159 | 1.2483 | 1 |
Where the last column index_no provides the index number of the closest coordinates from table_2, and populate id_1 3 times to provide the 3 closest matches in any order by dist in km or m.