I have two list of coordinates, mapped_coords, unmapped_coords that are both a list of coordinates.
I want to take the unmapped_coords and for every element return the index of the point with the min distance in mapped_coord.
> head(mapped_coords)
[[1]]
[1] -79.2939 43.8234
[[2]]
[1] -79.7598 43.4381
[[3]]
[1] -79.4569 43.6693
[[4]]
[1] -81.2472 42.9688
[[5]]
[1] -79.1649 43.8073
[[6]]
[1] -79.7388 43.6753
str(mapped_coords)
List of 62815
$ : num [1:2] -79.3 43.8
$ : num [1:2] -79.8 43.4
$ : num [1:2] -79.5 43.7
Using the geosphere package I can use distHaversine to calculate the distance of aa pair but I'm not sure of how to do it over the entire list.
> distHaversine(unlist(unmapped_coords[1]), unlist(mapped_coords[1]))
[1] 100594.6
You can use geosphere::distm
to make a distance matrix, of which you can find the minimum column (besides the diagonal, which is not useful) with which.min
:
l <- list(c(-79.2939, 43.8234),
c(-79.7598, 43.4381),
c(-79.4569, 43.6693),
c(-81.2472, 42.9688),
c(-79.1649, 43.8073),
c(-79.7388, 43.6753))
m <- geosphere::distm(do.call(rbind, l))
diag(m) <- NA
apply(m, 1, which.min)
#> [1] 5 6 1 2 1 3
If you have a second list of distances, pass that as the second parameter to distm
, making the diagonal useful. Since there will be no NA
s, the minimum column can be calculated with max.col(-m)
.
You can give as input to distHaversine
a pair of coordinates and a matrix of coordinates (with 2 columns), and that will return a vector of distances of the same length as the number of rows in the matrix. You can loop through your list of unmapped coordinates using lapply
:
Data:
mapped_coord = list(c(-79.29,43.82),c(-79.76,43.44))
[[1]]
[1] -79.29 43.82
[[2]]
[1] -79.76 43.44
unmapped_coord = list(c(-79.16,43.12),c(-80.52,42.95))
[[1]]
[1] -79.16 43.12
[[2]]
[1] -80.52 42.95
Method:
library(geosphere)
## Transform the list of mapped coordinates into a matrix
mat = do.call(rbind,mapped_coord)
[,1] [,2]
[1,] -79.29 43.82
[2,] -79.76 43.44
## Find the coordinates with the min distances
lapply(unmapped_coord,function(x) which.min(distHaversine(x,mat)))
[[1]]
[1] 2
[[2]]
[1] 2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.