我正在尝试执行一个重试函数,它将接受我想要做的事情作为参数,以及停止之前应该尝试的次数。
我想出了以下内容:
retry <- function(a, max = 10, init = 0){tryCatch({
if(init<max) a
}, error = function(e){retry(a, max, init = init+1)})}
现在我想测试它并确保它按我的预期工作,但我希望有人仔细检查,也许可以就我应该进一步测试的内容提供建议。
为了测试它并看看会发生什么,我这样修改了我的函数:
retry <- function(a, max = 10, init = 0){
tryCatch({
if(init<max) {
print(init) # added part
a
}
}, error = function(e){retry(a, max, init = init+1)})}
我正在使用 stop()
生成错误并对其进行测试。它似乎或多或少地按照我的意图工作......
> retry(stop())
[1] 0
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
但是...
There were 45 warnings (use warnings() to see them)
> warnings()
Messages d`avis :
1: In doTryCatch(return(expr), name, parentenv, handler) :
restarting interrupted promise evaluation
# (the 45 error messages are the same, the last one being the following)
45: In doTryCatch(return(expr), name, parentenv, handler) :
restarting interrupted promise evaluation
所以我的问题:
- 它似乎按我想要的方式工作,对吧?
- 我可以安全地忽略这些警告吗?
注意:警告的数量似乎取决于参数 max
的值,遵循以下模式:
max nb of warnings
1 no warning
2 1
3 3
4 6
5 10
6 15
7 21
8 28
9 36
10 45
最佳答案
你正试图破坏 promise a
。正确的解决方案是使用 substitute
或 rlang::enexpr
。我已经将一些代码放在一起作为包 retry
library(retry)
f <- function(x) {
if (runif(1) < 0.9) {
stop("random error")
}
x + 1
}
# keep retring when there is a random error
retry(f(1), when = "random error")
#> [1] 2
# keep retring until a requirement is satisified.
retry(f(1), until = function(val, cnd) val == 2)
#> [1] 2
# or using one sided formula
retry(f(1), until = ~ . == 2)
#> [1] 2
关于r - 在 R 中创建 "retry"函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37379472/