I have a list of data points with lat/lon coordinates that I want to associate with their country. There is a great answer on how to do this using rworldmaps here, which is reproduced in the example below. However, because of the relatively large grid size of my data (plus previous spatial interpolation), a not insignificant number of coastal data points end up falling outside the country boundaries of rworldmaps. Is there any way to associate these points with the nearest country to avoid losing the coastal data?
Here is the coords2country function:
library(sp)
library(rworldmap)
#Function code from: https://stackoverflow.com/questions/14334970/convert-latitude-and-longitude-coordinates-to-country-name-in-r?rq=1
coords2country = function(points)
{
countriesSP <- getMap(resolution='low')
#countriesSP <- getMap(resolution='high') #high res version
#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
}
Here is a sample of coordinate points and the response, with some missing coastal data points
pts <- data.frame(x = c(21.00, 21.25, 21.00, 21.25, 25.25, 25.75, 25.25, 25.75, 22.75, 26.50, 23.00),
y = c(65.75, 65.75, 65.50, 65.50, 65.00, 65.00, 64.75, 64.75, 63.75, 60.50, 60.00))
pts$country <- coords2country(pts)
head(pts)
x y country
1 21.00 65.75 Sweden
2 21.25 65.75 Sweden
3 21.00 65.50 Sweden
4 21.25 65.50 Sweden
5 25.25 65.00 <NA>
6 25.75 65.00 Finland
I'd like to modify this to count points such as x=25.25, 65.00 as part of Finland, or even capture a point that falls into the nearby ocean.
Note: Using the high resolution version of rworldmaps (with rworldxtra) does eliminate some of the NAs, but doesn't eliminate the problem.