AIM:我正在尝试使用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])
问题:我怎样才能让它忽略它找不到的地址并将它们保留为 NA 并继续搜索其余地址而不是停止。我有 2,000 个地址,很可能找不到几个。
由于我既没有示例数据(请始终在您的问题中提供数据(和 也不知道我正在演示的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"
使用 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")}
)
我自己无法测试这一点,所以希望我关闭了所有括号,但你明白它的要点。