How to stop a function in R that is taking too long and give it an alternative?

前端 未结 3 1053
离开以前
离开以前 2021-02-05 08:02

I\'m trying to do a thing \"the right way\". Sometimes \"the right way\" takes too long, depending on the inputs. I can\'t really know a priori when this will be. When \"the

3条回答
  •  太阳男子
    2021-02-05 08:47

    For anyone who wants a lighter weight solution that does not depend on the R.utils package, I ended up using a minimal solution based on the withTimeout() code.

    foo <- function() {
    
      time_limit <- 10
    
      setTimeLimit(cpu = time_limit, elapsed = time_limit, transient = TRUE)
      on.exit({
        setTimeLimit(cpu = Inf, elapsed = Inf, transient = FALSE)
      })
    
      tryCatch({
        # do some stuff
      }, error = function(e) {
        if (grepl("reached elapsed time limit|reached CPU time limit", e$message)) {
          # we reached timeout, apply some alternative method or do something else
        } else {
          # error not related to timeout
          stop(e)
        }
      })
    
    }
    

提交回复
热议问题