R 使用反向地理编码功能时,如何处理缺少的值?

R 使用反向地理编码功能时,如何处理缺少的值?,r,maps,geocoding,latitude-longitude,R,Maps,Geocoding,Latitude Longitude,我目前正在R中使用(N/271848),如下所示: Observation Longitude Latitude -------------------------------------- 1 116.38800 39.928902 2 53.000000 32.000000 3 NA NA 4 NA NA 我正在使用以下

我目前正在R中使用(N/271848),如下所示:

Observation   Longitude     Latitude
--------------------------------------
      1        116.38800    39.928902
      2        53.000000    32.000000
      3          NA          NA
      4          NA          NA
我正在使用以下帖子中的反向地理编码功能:

当我运行
coords2country(points)
行时,我得到以下错误:

“CheckNumericImpresse2Double(obj)中出错:非有限坐标”

我最好的猜测是函数不知道如何处理缺少的值。当我在观察的子集(不包括NA/缺失值)上运行代码时,它是有效的

我试图稍微修改函数(见下面最后一行)来解决这个问题,但仍然产生了上面提到的错误

可复制示例:

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 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
        }

Data最好用这个:

coords2country_NAsafe <- function(points)
{
    bad <- with(points, is.na(lon) | is.na(lat))
    result <- character(length(bad))
    result[!bad] <- coords2country(points[!bad,])
    result
}

coords2country\u NAsafe我正在使用rworldmaps包。当我执行您上面提供的代码并上载RgoogleMaps库时,我不断收到以下错误:coords2country中的错误(points[!bad,]):找不到函数“getMap”@ealfons1,请键入
require(“rworldmap”)
,看看这是否可以修复它。实际上,您提供给我的代码最终正常工作,但现在我有了一个新问题。我在问题中最初提供的代码生成的值没有生成正确匹配的ISO3数值。例如,对于LAT=39.928902和长=116.388000(这是中国),我得到了一个ISO3代码为42(不存在的值)。