为什么R抛出错误"错误值[3L]:没有循环中断/下一步,跳到顶层"而不是进入循环的下一次迭代?我在R版本2.13.1(2011-07-08)
for (i in seq(10)) {
tryCatch(stop(), finally=print('whoops'), error=function(e) next)
}
Run Code Online (Sandbox Code Playgroud)
出现这个问题是因为我想在绘图失败时创建一个不同的图像或根本没有图像.使用joran方法的代码看起来像这样:
for (i in c(1,2,Inf)) {
fname = paste(sep='', 'f', i, '.png')
png(fname, width=1024, height=768)
rs <- tryCatch(plot(i), error=function(e) NULL)
if (is.null(rs)){
print("I'll create a different picture because of the error.")
}
else{
print(paste('image', fname, 'created'))
dev.off()
next
}
}
Run Code Online (Sandbox Code Playgroud)
小智 10
也许你可以试试:
for (i in seq(10)) {
flag <- TRUE
tryCatch(stop(), finally=print('whoops'), error=function(e) flag<<-FALSE)
if (!flag) next
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,一旦你进入你的error
函数,你就不再处于循环中。有一种方法可以解决这个问题:
for (i in seq(10)) {
delayedAssign("do.next", {next})
tryCatch(stop(), finally=print('whoops'),
error=function(e) force(do.next))
}
Run Code Online (Sandbox Code Playgroud)
虽然那是......好吧,hacky。也许有一种不那么hacky的方式,但我没有看到一个正确的方式。
(这是有效的,因为delayedAssign
每个循环都会发生,取消了force
)
编辑
或者你可以使用延续:
for (i in seq(10)) {
callCC(function(do.next) {
tryCatch(stop(), finally=print('whoops'),
error=function(e) do.next(NULL))
# Rest of loop goes here
print("Rest of loop")
})
}
Run Code Online (Sandbox Code Playgroud)
编辑
正如 Joris 指出的那样,您可能实际上不应该使用其中任何一个,因为它们读起来很混乱。但是如果你真的想next
循环调用,这就是方法:)。