How do I time out a lapply when a list item fails or takes too long?

后端 未结 1 440
旧巷少年郎
旧巷少年郎 2020-12-09 19:16

For several efforts I\'m involved in at the moment, I am running large datasets with numerous parameter combinations through a series of functions. The functions have a wrap

相关标签:
1条回答
  • 2020-12-09 19:39

    You may well be able to manage graceful-exits-upon-timout using a combination of tryCatch() and evalWithTimeout() from the R.utils package. See also this post, which presents similar code and unpacks it in a bit more detail.

    require(R.utils)
    
    myFun <- function(x) {Sys.sleep(x); x^2}
    
    ## evalWithTimeout() times out evaluation after 3.1 seconds, and then
    ## tryCatch() handles the resulting error (of class "TimeoutException") with 
    ## grace and aplomb.
    myWrapperFunction <- function(i) {
        tryCatch(expr = evalWithTimeout(myFun(i), timeout = 3.1), 
                 TimeoutException = function(ex) "TimedOut")
    }
    
    sapply(1:5, myWrapperFunction)
    # [1] "1"        "4"        "9"        "TimedOut" "TimedOut"
    
    0 讨论(0)
提交回复
热议问题