【问题标题】:how to handle error from geocode (ggmap R)如何处理来自地理编码的错误(ggmap R)
【发布时间】:2015-06-11 02:00:04
【问题描述】:

我正在使用 ggmap 来查找位置。某些位置会产生错误。例如,

library(ggmap)

loc = 'Blue Grass Airport'
geocode(loc, output = c("more"))

结果

Error in data.frame(long_name = "Blue Grass Airport", short_name = "Blue Grass Airport",  : 
  arguments imply differing number of rows: 1, 0

如果我无法获得某些位置的结果也没关系,但我正在尝试处理列表中的 100 个位置。那么有没有办法获得 NA 而不是错误并让事情继续下去?例如,

library(ggmap)

loc = c('Blue Grass Airport', 'Boston MA', 'NYC')
geocode(loc, output = c("more"))

应该生成

NA
Result for Boston
Result for New York City

【问题讨论】:

    标签: r google-geocoder ggmap


    【解决方案1】:

    您可以使用 R tryCatch() 函数优雅地处理这些错误:

    loc = 'Blue Grass Airport'
    x <- tryCatch(geocode(loc, output = c("more")),
                  warning = function(w) {
                                print("warning"); 
                                # handle warning here
                            },
                  error = function(e) {
                              print("error");
                              # handle error here
                          })
    

    如果您打算使用for 循环或使用apply 函数显式循环位置,那么tryCatch() 也应该派上用场。

    【讨论】:

    • 谢谢@Tim Biegeleisen。这是否必须与forapply 一起使用?有没有办法可以输入列表loc = c(loc1, loc2, loc3)
    • 你可以使用lapply(loc, function(x) { y &lt;- tryCatch(geocode(x, output = c("more")), ...)
    • 对于大多数事情可能最好使用ggmap::geocode(),但taRifx.geo::geocode 有一个data.frame 方法,它只自动填写NA 观察结果,还使用try 来捕获错误和突突无论如何。
    猜你喜欢
    • 1970-01-01
    • 2019-05-18
    • 1970-01-01
    • 2018-10-10
    • 2017-12-22
    • 2019-04-22
    • 2014-05-27
    • 1970-01-01
    • 2017-08-04
    相关资源
    最近更新 更多