R循环中的Catch API无结果响应

x4shl7ld  于 2023-01-22  发布在  其他
关注(0)|答案(1)|浏览(91)

我一直在寻找如何与R函数中的API错误交互,但没有成功。我找到了tryCatch()的解决方案,但我没有意识到这一点,所以我决定在这里询问。
我有一个数据集,如下所示。

fluxo <-
  structure(list(code_o = c("355030802000004", "355030802000012", "355030802000013",
                            "355030802000014", "355030802000030", "355030802000036"),
                 code_d = c("3503488", "3503488", "3503488", "3503488", "3503488",  "3503488"),
                 fx = c(-46.70104009, -46.69845387, -46.69815333, 
                        -46.70141047, -46.69755981, -46.69996442),
                 fy = c(-23.55023455, -23.54720393, -23.55123612,
                        -23.55210794, -23.54364215, -23.55333346),
                 tx = c(-46.7224721383401, -46.7224721383401, -46.7224721383401,
                        -46.7224721383401, -46.7224721383401, -46.7224721383401),
                 ty = c(-23.5375321244996, -23.5375321244996, -23.5375321244996,
                        -23.5375321244996, -23.5375321244996, -23.5375321244996)),
            .Names = c("code_o", "code_d", "fx", "fy", "tx", "ty"),
            row.names = c(NA, 6L), class = "data.frame")

为了找到code_o和code_d点之间的距离和旅行时间,我使用了stplanr包中的dist_google()函数,它与Google Distance Matrix API交互。该函数只得到所有对所有的结果(所有code_o到所有code_d),我只需要给定的行对。因此,我编写了下面的for循环来完成这个任务。

library(stplanr)

tempos_falta_ubs <- data.frame()

for (linha in 1:nrow(fluxo)) {
  origin <- fluxo[linha, 3:4]
  destiny  <- fluxo[linha, 5:6]
  tempos_falta_ubs <- rbind(tempos_falta_ubs,
                   dist_google(from=origin,
                               to=destiny,
                               mode='walking'))
}

但有时它会返回以下错误消息:
错误:没有此请求的结果(例如,由于发件人和收件人位置之间不支持此模式)。
当这种情况发生时,我想跳过这一行对,在tempos_falta_ubs中再输入一行(所有列都是NA),然后继续下一行。我是手动完成的,但它很糟糕。我怎么能在不停止循环的情况下自动完成呢?
先谢了。

omjgkv6w

omjgkv6w1#

empty_line <- structure(list(
  from_addresses = NA_character_, to_addresses = NA_character_, 
  distances = NA_integer_, duration = NA_integer_, currency = NA, fare = NA
), .Names = c("from_addresses", "to_addresses", "distances", "duration", "currency", "fare"), 
row.names = "NA", class = "data.frame")

for (linha in seq_len(nrow(fluxo))) {
  origin <- fluxo[linha, 3:4]
  destiny  <- fluxo[linha, 5:6]
  x <- tryCatch(dist_google(from=origin, to=destiny, mode='walking'), error = function(e) empty_line)
  tempos_falta_ubs <- rbind(tempos_falta_ubs, x)
}

相关问题