Monday, 19 August 2013

Converting latitude and longitude to country in R: Error in .checkNumericCoerce2double(obj) : non-finite coordinates

Converting latitude and longitude to country in R: Error in
.checkNumericCoerce2double(obj) : non-finite coordinates

I am currently working with data (N of 271,848) in R that looks as follows:
Observation Longitude Latitude
1 116.38800 39.928902
2 53.000000 32.000000
3 NA NA
4 NA NA
And I am using the function code derived in the following post: Convert
latitude and longitude coordinates to country name in R
When I run the code to generate the country values, coords2country(points)
, I get the following error:
"Error in .checkNumericCoerce2double(obj) : non-finite coordinates"
My best guess is that it has something to do with the function not knowing
what to do with missing values (NA). When I ran the code on a subset of
observations (excluding NA's/missing values), it worked just fine. I
proceeded to modify the function slightly (see last line below), but that
still produced the error I am referring to above. Could somebody please
help me do the following:
Modify the code to properly handle NA's (or missing values).
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
+datum=wgs84"))
#! andy modified to make the CRS the same as rworldmap
#pointsSP = SpatialPoints(points, proj4string=CRS("+proj=longlat
+ellps=WGS84 +datum=WGS84 +no_defs"))
# 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 # returns the ISO3 code
#The line below is what I thought could resolve the problem.
na.action = na.omit
}

No comments:

Post a Comment