R 如果找不到地址,则继续循环
目标:我正在尝试从ggmaps中使用get_map函数检索一系列地图 当我使用纬度和经度时,我知道以下方法有效:R 如果找不到地址,则继续循环,r,lapply,ggmap,R,Lapply,Ggmap,目标:我正在尝试从ggmaps中使用get_map函数检索一系列地图 当我使用纬度和经度时,我知道以下方法有效: houses_maps <- lapply(latlon, function(x) get_map(location = x, zoom = 20, maptype = "satellite
houses_maps <- lapply(latlon,
function(x)
get_map(location = x,
zoom = 20,
maptype = "satellite",
source = "google"))
问题:我如何让它忽略它找不到的地址,让它们不存在,继续搜索其余的地址,而不是停止。我有2000个地址,可能找不到几个。因为我没有示例数据,请始终在您的问题和答案中提供数据 也不知道我正在演示的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")}
)
我自己不能测试这个,所以希望我关闭了所有的括号,但你明白它的要点 使用try或traCatch忽略或处理错误。@RYoda您能给我一个tryCatch示例吗?这可能是因为它找不到一个地址Nope。您的Google Maps API密钥很可能未启用地理编码。请尝试geocodetomet,6-10,25720 Bellver de Cerdanya,Lleida,西班牙,输出=全部确认。。
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")}
)