Search code examples
rterra

R terra + geodata: How to map lon,lat to identify country or US state?


I have downloaded and installed libraries terra and geodata in R.

I am now trying to give a list of coordinate pairs (lon,lat) and find out which country (or US state) it is in. the right start is

library(geodata)
usa <- gadm(country="USA", level=1, path=tempdir())
wld <- world(path=tempdir())

I know from a plot(usa) and plot(w) that I now have the map coordinates down to the state level for the US and the full world map, but I don't know how to inquire about (lon,lat) points. Point ers to the right function would be appreciated.


Added: I obviously was not clear enough. The question and answer (thx, robert) were indeed:

> mypoints <- rbind(c(lon=-100,lat=34), 
              c(-118,34),c(-90,40),
              c(-80,40),c(-73.961,40.786))
> terra::extract(usa,mypoints)
  id.y    GID_1 GID_0       COUNTRY       NAME_1                       VARNAME_1 NL_NAME_1 TYPE_1 ENGTYPE_1 CC_1 HASC_1 ISO_1
1    1 USA.44_1   USA United States        Texas                         TX|Tex.      <NA>  State     State <NA>  US.TX US-TX
2    2  USA.5_1   USA United States   California                       CA|Calif.      <NA>  State     State <NA>  US.CA US-CA
3    3 USA.14_1   USA United States     Illinois                         IL|Ill.      <NA>  State     State <NA>  US.IL US-IL
4    4 USA.39_1   USA United States Pennsylvania Commonwealth of Pennsylvania|PA      <NA>  State     State <NA>  US.PA US-PA
5    5 USA.33_1   USA United States     New York                         NY|N.Y.      <NA>  State     State <NA>  US.NY US-NY

and now easy:

> terra::extract(usa, mypoints)$NAME_1
[1] "Texas"        "California"   "Illinois"     "Pennsylvania" "New York"

this is very sensitive ---for example, a point in the Hudson river is not part of NY, but NA.


Solution

  • It is not clear what exactly you are after, but my guess is that you are looking for terra::extract.

    Example data

    library(terra)
    v <- vect(system.file("ex/lux.shp", package="terra"))
    pts <- cbind(c(5.90, 6.17), c(49.94, 49.60))
    plot(v)
    points(pts, col="red", pch=20)
    

    Query the polygons for each point

    extract(v, pts)
    #  id.y ID_1     NAME_1 ID_2     NAME_2 AREA    POP
    #1    1    1   Diekirch    5      Wiltz  263  16735
    #2    2    3 Luxembourg   10 Luxembourg  237 182607