How to retry a statement on error?

后端 未结 6 1270
慢半拍i
慢半拍i 2020-12-01 06:19

How can I simply tell R to retry a statement a few times if it errors? E.g. I was hoping to do something like:

tryCatch(dbGetQuery(...),           # Query da         


        
6条回答
  •  遥遥无期
    2020-12-01 06:44

    I usually put the try block in a loop, and exit the loop when it no longer fails or the maximum number of attempts is reached.

    some_function_that_may_fail <- function() {
      if( runif(1) < .5 ) stop()
      return(1)
    }
    
    r <- NULL
    attempt <- 1
    while( is.null(r) && attempt <= 3 ) {
      attempt <- attempt + 1
      try(
        r <- some_function_that_may_fail()
      )
    } 
    

提交回复
热议问题