限制函数在R for循环中处理的时间 [英] Limiting the time that a function processes in an R for loop
问题描述
我想应用一个函数(foo作为这个解释)来将一个数据向量转换成另一个值。此功能将数据作为输入,并需要将表单提交给网页。有时候,这个过程很快,而其他时间呢,可以很长一段时间。我想运行for循环(或等价的应用函数),以跳过需要太长时间的项目。我试图限制循环运行的时间,然后跳到下一个5秒,使用下面的代码:
pre $ pb < - (i = 1:100)中的txtProgressBar(min = 1,max = 100,style = 3)
存储< - matrix(nrow = sample.length,ncol = 2)
($系统时间())
存储[i,] < - try(foo(data.vec [i]),TRUE)
- s> 5){next}
#update progress bar
setTxtProgressBar(pb,i)
}
close(pb)
我认为我不能理解如何在for循环中应用next条件。已经搜索找到一个更清楚的解释,但没有得到任何好运在这里。
evalWithTimeout / code>与 tryCatch()
协同工作,可能会提供更简洁的解决方案
例如:
$ p $ require(R.utils)
for(i in 1:5){
tryCatch(
expr = {
evalWithTimeout({Sys.sleep(i); cat(i,\
),
TimeoutException = function(ex)cat(Timeout。Skipping.\\\
)
)
}
#1
#2
#3
#超时。跳绳。
#超时。跳绳。
在上面的示例中:
-
evalWithTimeout()
的第一个参数包含要在每个循环内进行评估的代码。 $ b -
evalWithTimeout()
的超时
参数设置了以秒为单位的时间限制。tryCatch()
的参数TimeoutException
参数在循环迭代超时时执行的函数。
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)
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.
解决方案evalWithTimeout()
from packageR.utils
, in concert withtryCatch()
, might provide a cleaner solution.For example:
require(R.utils) for(i in 1:5) { tryCatch( expr = { evalWithTimeout({Sys.sleep(i); cat(i, "\n")}, timeout = 3.1) }, TimeoutException = function(ex) cat("Timeout. Skipping.\n") ) } # 1 # 2 # 3 # Timeout. Skipping. # Timeout. Skipping.
In the artificial example above:
The first argument to
evalWithTimeout()
contains the code to be evaluated within each loop.The
timeout
argument toevalWithTimeout()
sets the time limit in seconds.The
TimeoutException
argument totryCatch()
takes a function that is to be executed when an iteration of the loop is timed out.
这篇关于限制函数在R for循环中处理的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!