[GIS] Assign country names to long and lat in R

rraster

I have gridded data on temperature, from which I want to extract data for specific countries. Put it in another way, I want to kind of assign country names to the coordinates (long and lat). The way I am trying to accomplish it:

library(gapminder)
df = map_data("world") %>% select(long, lat, region)  
r = rasterFromXYZ(df)

If I got a raster from df, then I could adjust the resolution and extent to merge it with my data on temperature. Then, I could convert it to a dataframe and subset by country. But when I try to raster df, I get an error message:

"Error in rasterFromXYZ(df) : x cell sizes are not regular".

How can I make it regular? Or is there any other easy way to assign country names to the coordinates?

Best Answer

You can use the geonames package to query the geonames.org server:

> library(geonames)
> options(geonamesUsername="getafreeusernamefromgeonames.org")
> GNcountryCode(lat=54, lng=-2)
$languages
[1] "en-GB,cy-GB,gd"

$distance
[1] "0"

$countryCode
[1] "GB"

$countryName
[1] "United Kingdom of Great Britain and Northern Ireland"

Note that locations in the sea will trigger an error, which you'll have to trap if you are in a loop (you can only do one query at a time):

> GNcountryCode(lat=0, lng=0)
Error in getJson("countryCode", list(lat = lat, lng = lng, radius = radius,  : 
  error code 15 from server: no country code found