限制函数在R for循环中处理的时间

exl*_*exl 7 loops for-loop r

我想应用一个函数(这个解释为"foo")将数据向量转换为另一个值.此函数将数据作为输入,并需要将表单提交到网页.有时候,这很快就会发生,而其他时候,这可能需要很长时间.我想以跳过花费太长时间的项目的方式运行for循环(或等效的apply函数).我尝试使用以下内容限制循环运行的时间,然后跳到下一个5秒:

pb <- txtProgressBar(min = 1, max = 100, style = 3)
storage <- matrix(nrow = sample.length, ncol = 2)

for(i in 1:100){  
     s <- Sys.time()  
     storage[i,] <- try(foo(data.vec[i]), TRUE)  
     if (Sys.time() - s >5) {next}  
     # update progress bar  
     setTxtProgressBar(pb, i)  
}  
close(pb)  
Run Code Online (Sandbox Code Playgroud)

我认为我不能理解如何在for循环中应用'next'条件.我们已经寻找更清楚的解释,但这里没有运气.

Jos*_*ien 12

withTimeout()与包装R.utils一起tryCatch(),可以提供更清洁的解决方案.

例如:

require(R.utils)

for(i in 1:5) {
    tryCatch(
        expr = {
            withTimeout({Sys.sleep(i); cat(i, "\n")}, 
                         timeout = 3.1)
            }, 
        TimeoutException = function(ex) cat("Timeout. Skipping.\n")
    )
}

# 1 
# 2 
# 3 
# Timeout. Skipping.
# Timeout. Skipping.
Run Code Online (Sandbox Code Playgroud)

在上面的仿制例子中:

  • 第一个参数withTimeout()包含要在每个循环中计算的代码.

  • timeout用于withTimeout()设置时间限制的参数(以秒为单位).

  • 获取将在循环的迭代超时时执行的函数的TimeoutException参数tryCatch().

  • 我的循环坏了。如何恢复呢?` checkError(res) 中的错误:httr 调用中出现未定义的错误。httr 输出:操作被应用程序回调中止` (2认同)