Search code examples
rdistancespatial

How to look for the closest place based on coordinates


I have a main database with several weather stations. Each station has coordinates in Decimal degrees. Below just an example, as coordinates were made up

stationid lon lat
1a        80  104
1b        84  110
1c        85  111

Aside, i have a smaller dataset with places. i require to match each place to the closest weather station from the main database (hopefully with a specified distance threshold)

  place lon   lat 
  2a    80.5  104.1
  3b    83    109

So the resulting smaller database will show

  place lon   lat    stationid
  2a    80.5  104.1  1a
  3b    83    109    1b

will appreciate any ideas


Solution

  • Try geosphere::distm + max.col

    df2$stationid <- df1$stationid[max.col(-distm(rev(df2[-1]), rev(df1[-1])))]
    

    which gives

      place  lat   lon stationid
    1    2a 80.5 104.1        1a
    2    3b 83.0 109.0        1b