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

前端 未结 3 1055
离开以前
离开以前 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:53

    The R package R.utils has a function evalWithTimeout that's pretty much exactly what you're describing. If you don't want to install a package, evalWithTimeout relies on the less user friendly R base function setTimeLimit

    Your code would look something like this:

    library(R.utils)
    
    slow.func <- function(x){
      Sys.sleep(10)    
      return(x^2)
    }
    
    fast.func <- function(x){
      Sys.sleep(2) 
    return(x*x)
    }
    interruptor = function(FUN,args, time.limit, ALTFUN){
      results <- NULL
      results <- evalWithTimeout({FUN(args)},timeout=time.limit,onTimeout="warning")
      if(results==NULL){
        results <- ALTFUN(args)
      }
      return(results)
    }   
    interruptor(slow.func,args=2,time.limit=3,fast.func)
    

提交回复
热议问题