代码之家  ›  专栏  ›  技术社区  ›  delcast

如果找不到地址,继续循环

  •  0
  • delcast  · 技术社区  · 6 年前

    目的: 我正在尝试使用 get_map 函数从 ggmaps .

    当我使用经度和纬度时,我知道以下工作:

    houses_maps <- lapply(latlon,
                      function(x)
                        get_map(location = x,
                                zoom = 20, 
                                maptype = "satellite", 
                                source = "google")) 
    

    问题: 当我使用地址而不是纬度和经度时,它不会完成循环。这可能是因为它找不到其中一个地址,例如“Tomet,6-10,25720 Bellver de Cerdanya,Lleida,Spain”

    我得到这个错误:

    Error in data.frame(ll.lat = ll[1], ll.lon = ll[2], ur.lat = ur[1], ur.lon = ur[2]) : 
      arguments imply differing number of rows: 0, 1
    In addition: Warning message:
    geocode failed with status ZERO_RESULTS, location = "tomet, 6-10, 25720 Bellver de Cerdanya, Lleida, Spain" 
    Called from: data.frame(ll.lat = ll[1], ll.lon = ll[2], ur.lat = ur[1], ur.lon = ur[2])
    

    问题: 我怎样才能让它忽略它找不到的地址,让它们不可用,继续搜索其余的地址而不是停止。我有2000个地址,可能找不到几个。

    2 回复  |  直到 6 年前
        1
  •  1
  •   R Yoda    6 年前

    因为我都没有示例数据(请始终提供您的问题中的数据),并且 也不知道 get_map 我正在演示的功能 这里的基本思想是:

    # simplified example data
    latlon = c("address 1", "address 2", "address 3")
    
    # mock the function
    get_map <- function(location, ...) {
      if (location == "address 2") stop(paste("geocode failed with status ZERO_RESULTS, location =", location))
      return(location)
    }
    
    
    houses_maps <- lapply(latlon,
                          function(x)
                            tryCatch(get_map(location = x,
                                       zoom = 20, 
                                       maptype = "satellite", 
                                       source = "google"),
                                     error = function(e) {
                                       print(e)
                                       return(NA)
                                     }))
    # <simpleError in get_map(location = x, zoom = 20, maptype = "satellite",
    # source = "google"): geocode failed with status ZERO_RESULTS,
    # location = address 2>    
    
    houses_maps                      
    # [[1]]
    # [1] "address 1"
    # 
    # [[2]]
    # [1] NA
    # 
    # [[3]]
    # [1] "address 3"
    
        2
  •  1
  •   Bogdan    6 年前

    使用try命令预先实际测试函数。在您的示例中,它应该是:

    houses_maps <- lapply(latlon,
                      function(x)
                      res <- try(get_map(location = x,
                                zoom = 20, 
                                maptype = "satellite", 
                                source = "google"))
                      if(inherits(res, "try-error")) next
                      else{
                        get_map(location = x,
                                zoom = 20, 
                                maptype = "satellite", 
                                source = "google")}
                      )
    

    我自己也不能测试这个,所以希望我把所有的括号都合上了,但你能理解其中的要点。