Вы можете использовать функцию tryCatch (), чтобы отлавливать ошибки и предупреждения и корректировать рабочий процесс в зависимости от результата, например:
x = -3.5
repeat{
x <- x + 0.6
print( paste("Current value of x is", x) )
result <- tryCatch( log( x ),
error = function(e) e,
warning = function(w) w )
if (inherits(result,"warning")) next # For warnings - continue the next iteration
if (inherits(result,"error")) stop( result ) # For errors - stop
print( paste0(" log(",x,")=", result))
break
}
# [1] "Current value of x is -2.9"
# [1] "Current value of x is -2.3"
# [1] "Current value of x is -1.7"
# [1] "Current value of x is -1.1"
# [1] "Current value of x is -0.5"
# [1] "Current value of x is 0.1"
# [1] " log(0.1)=-2.30258509299404"
Однако, будьте очень осторожны с циклами repeat и while, так как вы можете получить в итогесоздавая бесконечный цикл.Было бы неплохо проверить, сколько итераций выполнено циклом, и прервать его, если было слишком много итераций:
x = -3.5
iter <- 0
while (iter < 100) {
x <- x + 0.6
iter <- iter + 1
print( paste("Current value of x is", x) )
result <- tryCatch( log( x ),
error = function(e) e,
warning = function(w) w )
if (inherits(result,"warning")) next # For warnings - continue the next iteration
if (inherits(result,"error")) stop( result ) # For errors - stop
print( paste0(" log(",x,")=", result))
break
}