Wednesday, 21 August 2013

Reverse geocode latitude and longitude to country name R: Incorrect ISO3 values

Reverse geocode latitude and longitude to country name R: Incorrect ISO3
values

I am currently working with a dataset with over 27,000 observations. Each
observation has a latitude and longitude value. I am currently using R,
and posted previously about this project: Converting latitude and
longitude to country in R: Error in .checkNumericCoerce2double(obj) :
non-finite coordinates
Now, I am working with the rworldmaps package, and the following code:
library(sp)
library(rworldmap)
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
# new changes in worldmap means you have to use this new CRS (bogdan):
pointsSP = SpatialPoints(points, proj4string=CRS(" +proj=longlat
+ellps=WGS84 +datum=WGS84 +no_defs +towgs84=0,0,0"))
# 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 #would return the ISO3 code
}
#The function below fixes the NA error
coords2country_NAsafe <- function(points)
{
bad <- with(points, is.na(lon) | is.na(lat))
result <- character(length(bad))
result[!bad] <- coords2country(points[!bad,])
result
}
When I run the following command
coords2country_NAsafe(points)
I obtain ISO3 codes for my observations. However, they are incorrect ISO3
codes. I would like to know why the functions above and the rworldmaps
package would be producing the incorrect ISO3 codes. Furthermore, I would
really appreciate any help in finding a way of obtaining the correct ones
for each observation. In order to better facilitate this, I am providing a
link to a csv file containing the data I am working with here:
https://www.dropbox.com/s/xf72iywaqm2ulsm/points.csv

No comments:

Post a Comment