I have a list of latitude and longitude coordinates, and wish to find out which country they all reside in.
I modified an answer from this question about lat-long to
You can use my geonames
package to lookup from the http://geonames.org/ service:
> GNcountryCode(51.5,0)
$languages
[1] "en-GB,cy-GB,gd"
$distance
[1] "0"
$countryName
[1] "United Kingdom of Great Britain and Northern Ireland"
$countryCode
[1] "GB"
> GNcountryCode(44.5,20)
$languages
[1] "sr,hu,bs,rom"
$distance
[1] "0"
$countryName
[1] "Serbia"
$countryCode
[1] "RS"
Get it from r-forge because I'm not sure I bothered to release it to CRAN:
https://r-forge.r-project.org/projects/geonames/
Yes, it depends on an external service, but at least it knows what happened to communism... :)
Thanks for the carefully constructed question. It required just a couple of line changes to be able to use rworldmap (containing up-to-date countries) see below. I'm not an expert on CRS but I don't think the change I had to make to the proj4string makes any difference. Others might like to comment on that.
This worked for me & gave :
> coords2country(points)
[1] United Kingdom Belgium Germany Austria
[5] Republic of Serbia
All the best, Andy
library(sp)
library(rworldmap)
# The single argument to this function, points, is a data.frame in which:
# - column 1 contains the longitude in degrees
# - column 2 contains the latitude in degrees
coords2country = function(points)
{
countriesSP <- getMap(resolution='low')
#countriesSP <- getMap(resolution='high') #you could use high res map from rworldxtra if you were concerned about detail
# convert our list of points to a SpatialPoints object
# pointsSP = SpatialPoints(points, proj4string=CRS(" +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs +towgs84=0,0,0"))
#setting CRS directly to that from rworldmap
pointsSP = SpatialPoints(points, proj4string=CRS(proj4string(countriesSP)))
# use 'over' to get indices of the Polygons object containing each point
indices = over(pointsSP, countriesSP)
# return the ADMIN names of each country
indices$ADMIN
#indices$ISO3 # returns the ISO3 code
#indices$continent # returns the continent (6 continent model)
#indices$REGION # returns the continent (7 continent model)
}