在循环中重复值,直到错误消失 [英] Repeating values in loop until error disappears

查看:88
本文介绍了在循环中重复值,直到错误消失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用for循环使用Googleway软件包对大量地址进行地理编码.最初,我遇到了"500个内部服务器错误"的问题,从而停止了循环的执行.我能够使用tryCatch()解决此问题.但是,由于这往往是暂时性错误,因此我希望函数重复抛出错误的地址,直到它接收到结果或进行任意次尝试(例如10次)为止.

I am currently using a for loop to geocode a large number of addresses using the Googleway package. Initially, I ran into issues with "500 internal server errors" stopping the execution of the loop. I was able to get around this using tryCatch(). However, since this tends to be a transient error, I would like the function to repeat the address that throws the error until it receives a result or hits some arbitrary number of attempts, let's say 10.

不幸的是,我发现tryCatch()和与之相关的文档令人困惑,所以我不知该如何做,除了使它抛出错误消息并继续前进之外,什么都不做.这是我当前的代码:

Unfortunately, I've found tryCatch() and the documentation associated with it confusing, so I'm at a loss for how to do anything other than get it to throw an error message and move on. Here is my current code:

rugeocoder.fun <- function(addr){
              require(googleway)
              output <- vector("list", length=length(addr))
              tryCatch({
                for(i in 1:length(addr)){
                  output[[i]] <- google_geocode(address=addr[i], key="myapikey", language="ru", simplify=T)
                  print(i)

                }},error=function(e) output[[i]] <- "Error: reattempt")
              return(output)
              }

推荐答案

您可能想要分离出安全调用google_geocode()和循环访问地址的逻辑.

You probably want to separate out the logic for calling google_geocode() safely, and for looping over the addresses.

这是一个功能,该功能可以修改其他功能以反复调用它们,直到它们起作用为止,否则它们将失败max_attempts次.修改其他功能的功能有时称为副词".

Here's a function that modifies other functions to call them repeatedly until they work, or they fail max_attempts times. Functions that modify other functions are sometimes called "adverbs".

safely <- function(fn, ..., max_attempts = 5) {
  function(...) {
    this_env <- environment()
    for(i in seq_len(max_attempts)) {
      ok <- tryCatch({
          assign("result", fn(...), envir = this_env)
          TRUE
        },
        error = function(e) {
          FALSE
        }
      )
      if(ok) {
        return(this_env$result)
      }
    }
    msg <- sprintf(
      "%s failed after %d tries; returning NULL.",
      deparse(match.call()),
      max_attempts
    )
    warning(msg)
    NULL
  }
}

尝试使用此简单函数生成随机数,如果函数太小则会抛出错误.

Try it out on this simple function that generates a random number, and throws an error if it is too small.

random <- function(lo, hi) {
  y <- runif(1, lo, hi)
  if(y < 0.75) {
    stop("y is less than 0.75")
  }
  y
}
safe_random <- safely(random)
safe_random() # will sometimes work, will sometimes return NULL
safe_random(0, 10) # will usually work

在这种情况下,您想修改google_geocode()函数.

In you case, you want to modify the google_geocode() function.

safe_google_geocode <- safely(google_geocode)

然后遍历调用此地址的地址.

Then loop over addresses calling this.

geocodes <- lapply( # purrr::map() is an alternative
  addresses,
  safe_google_geocode,
  key = "myapikey", 
  language = "ru", 
  simplify = TRUE
)

这篇关于在循环中重复值,直到错误消失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆