Question
Joining lat/lon data frames by nearest distance
Let's say I have a regular latitude/longitude grid and data at irregular locations, like this:
grid = tidyr::crossing(lon = seq(0, 1, 0.25), lat = seq(0, 1, 0.25))
data = tibble::tibble(lon = runif(4), lat=runif(4), y=rnorm(4))
How do I use, for example, dplyr::inner_join
and join_by
to join these data frames so that I get y
values from data
and corresponding lat
and lon
values from grid
from the nearest location, i.e. the grid point with smallest (grid$lon - data$lon)^2 + (grid$lat - data$lat)^2
for each row in data
?