限制函数在 R for 循环中处理的时间 [英] Limiting the time that a function processes in an R for loop
问题描述
我想应用一个函数(本解释中的foo")将数据向量转换为另一个值.该函数以数据为输入,需要向网页提交表单.有时,这进行得很快,而有时,可能会持续很长时间.我想以跳过花费太长时间的项目的方式运行 for 循环(或等效的 apply 函数).我尝试使用以下方法限制循环运行的时间,然后再跳到接下来的 5 秒:
I want to apply a function ("foo" for this explanation) to tranform a vector of data into another value. This function takes the data as an input, and needs submit forms to webpages. Sometimes, this goes quickly, and other times, it can a long time. I would like to run the for loop (or equivalent apply function) in a way that skips over the items that take too long. I have tried to limit the time the loop runs before skipping to the next to 5 seconds using the following:
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)
我想我一定不明白如何在 for 循环中应用下一个"条件.已经搜索找到更清晰的解释,但在这里没有任何运气.
I think that I must not be understanding how to apply the 'next' condition in a for loop. have searched to find a clearer explanation, but not getting any luck here.
推荐答案
withTimeout()
来自包 R.utils
,与 tryCatch()<一致/code>,可能会提供更简洁的解决方案.
withTimeout()
from package R.utils
, in concert with tryCatch()
, might provide a cleaner solution.
例如:
require(R.utils)
for(i in 1:5) {
tryCatch(
expr = {
withTimeout({Sys.sleep(i); cat(i, "
")},
timeout = 3.1)
},
TimeoutException = function(ex) cat("Timeout. Skipping.
")
)
}
# 1
# 2
# 3
# Timeout. Skipping.
# Timeout. Skipping.
在上面的人工例子中:
withTimeout()
的第一个参数包含要在每个循环中计算的代码.
The first argument to
withTimeout()
contains the code to be evaluated within each loop.
withTimeout()
的 timeout
参数以秒为单位设置时间限制.
The timeout
argument to withTimeout()
sets the time limit in seconds.
tryCatch()
的 TimeoutException
参数采用一个函数,该函数将在循环迭代超时时执行.
The TimeoutException
argument to tryCatch()
takes a function that is to be executed when an iteration of the loop is timed out.
这篇关于限制函数在 R for 循环中处理的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!