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:

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?

  • How many countries are in your area of interest? You could do an overlay with the administrative boundaries, for example from gadm.org
    – SMiller
    Commented Oct 2, 2018 at 14:17

2 Answers 2


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

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

[1] "0"

[1] "GB"

[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

Please put the libraries in your code, or use ::; it's time consuming to have to infer what packages might be in your namespace.

Your data is irregular points. If you just want them in a dataframe, then covert them to sf or sp objects. Your data values are also nominal, so unless you want to calculate proportions there's no sensible way to convert that to a raster.

To join country names to your data I recommned rnaturalearth, my solution also uses sf


dfr <- map_data("world") %>% select(long, lat, region)
sfRegion <- st_as_sf(dfr, coords=c('long', 'lat'))
sfCountry <- ne_countries(returnclass='sf')
sfJoined <- st_join(sfCountry, sfRegion)

As it turns out, the rnaturalearth data has a lot of detail on regions and subregions, so you may could just use it. I don't know about map_data but it might also have country names already available.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.