【问题标题】:How to handle missing values when using a reverse geocode function?使用反向地理编码功能时如何处理缺失值?
【发布时间】:2013-08-19 23:57:54
【问题描述】:

我目前在 R 中使用 data(N of 271,848),如下所示:

Observation   Longitude     Latitude
--------------------------------------
      1        116.38800    39.928902
      2        53.000000    32.000000
      3          NA          NA
      4          NA          NA

我正在使用以下帖子中的反向地理编码功能:Convert latitude and longitude coordinates to country name in R

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

“.checkNumericCoerce2double(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
        }

【问题讨论】:

    标签: r maps geocoding latitude-longitude


    【解决方案1】:

    最好改用这个:

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

    【讨论】:

    • 我正在使用 rworldmaps 包。当我执行您上面提供的代码并上传 RgoogleMaps 库时,我不断收到以下错误: coords2country(points[!bad, ]) 中的错误:找不到函数“getMap”
    • @elfons1,请输入require("rworldmap") 看看是否能解决问题。
    • 实际上,您提供给我的代码最终可以正常工作,但现在我遇到了一个新问题。我最初在我的问题中提供的代码产生的值没有产生正确匹配的 ISO3 数值。例如,对于 lat=39.928902 和 long=116.388000(即中国),我得到的 ISO3 代码为 42(不存在的值)。
    • @elfons1,考虑发布一个新问题,并附上您的新问题的最小可重现示例。
    猜你喜欢
    • 1970-01-01
    • 2021-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-31
    相关资源
    最近更新 更多