具有步骤执行时间限制的For循环

ins*_*ven 3 r

我想对for循环的每个步骤的执行时间进行限制。简而言之,如果该步骤在10秒内未完成,请转到next

更具体地说,这是一些代码。

myComplicatedFunction <- function(obj, ...) { <some code here> }
x # something to process
x_result <- vector(mode = "list", length = length(x))
for (i in seq_along(x)) {
    x_result[[i]] <- 
        processNotMoreThanXSeconds(
            givenTime = 10,
            myComplicatedFunction(x[i]),
            didNotComplete = function() "Time's up!"
        )
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,如何声明这样的功能processNotMoreThanXSeconds

Lyz*_*deR 6

您可以使用setTimeLimit(它是基本R的一部分):

setTimeLimit({

  Sys.sleep(7)

}, elapsed = 5)
Run Code Online (Sandbox Code Playgroud)

如果达到时间限制,该函数将返回错误(例如,如果您运行上述操作,则处理需要7秒,但限制为5)。您可以将其捆绑在一起try以处理错误并继续循环:

myerror <- try({

   setTimeLimit({

     Sys.sleep(7)

   }, elapsed = 5)
}, silent = TRUE)

class(myerror)
#[1] "try-error"
Run Code Online (Sandbox Code Playgroud)

然后使用if-else语句检查是否有错误并继续。就像是:

if (class(myerror) == 'try-error') {
  next
} 
Run Code Online (Sandbox Code Playgroud)