r - How to handle missing values when using a reverse geocode function? -
i working data (n of 271,848) in r looks follows:
observation longitude latitude -------------------------------------- 1 116.38800 39.928902 2 53.000000 32.000000 3 na na 4 na na
and using reverse geocode function following post: convert latitude , longitude coordinates country name in r
when run coords2country(points)
line, following error:
"error in .checknumericcoerce2double(obj) : non-finite coordinates"
my best guess function not know how treat missing values. when run code on subset of observations (excluding na's/missing values), works.
i attempted modify function (see last line below) fix problem, still produced error referring above.
reproducible example:
data <- data.frame( observation = 1:5, longitude = c(116.3880005, 53, -97, na, na), latitude = c(39.92890167, 32, 32, na, na)) library(sp) library(rworldmap) coords2country = function(points) { countriessp <- getmap(resolution='low') #countriessp <- getmap(resolution='high') #you use high res map rworldxtra if concerned detail # convert our list of points spatialpoints object #pointssp = spatialpoints(points, proj4string=crs("+proj=longlat +datum=wgs84")) #! andy modified make crs same rworldmap #pointssp = spatialpoints(points, proj4string=crs("+proj=longlat +ellps=wgs84 +datum=wgs84 +no_defs")) # new changes in worldmap means have use new crs (bogdan): pointssp = spatialpoints(points, proj4string=crs(" +proj=longlat +ellps=wgs84 +datum=wgs84 +no_defs +towgs84=0,0,0")) # use 'over' indices of polygons object containing each point indices = over(pointssp, countriessp) # return admin names of each country indices$admin #indices$iso3 # returns iso3 code #the line below thought resolve problem. na.action = na.omit }
better use instead:
coords2country_nasafe <- function(points) { bad <- with(points, is.na(lon) | is.na(lat)) result <- character(length(bad)) result[!bad] <- coords2country(points[!bad,]) result }
Comments
Post a Comment