这里有两种方法,都带有lapply循环,只是错误函数返回的内容不同。
错误消息显示为message,而不是cat。这是因为在包中使用cat 或print 是不受欢迎的。
1。返回索引i
result <- lapply(1:15, function(i) {
tryCatch({
print(i)
if (i==7) stop("Urgh, the iphone is in the blender !")
if (i==9) stop("Urgh, the iphone is in the blender !")
if (i==14) stop("Urgh, the iphone is in the blender !")
}, error=function(e){
msg <- paste("ERROR :", conditionMessage(e))
message(msg)
i
})
})
#[1] 1
#[1] 2
#[1] 3
#[1] 4
#[1] 5
#[1] 6
#[1] 7
#ERROR : Urgh, the iphone is in the blender !
#[1] 8
#[1] 9
#ERROR : Urgh, the iphone is in the blender !
#[1] 10
#[1] 11
#[1] 12
#[1] 13
#[1] 14
#ERROR : Urgh, the iphone is in the blender !
#[1] 15
unlist(result)
#[1] 7 9 14
2。返回错误e
此解决方案返回错误本身,以后可以检索该错误。 message 的输出被省略。
result <- lapply(1:15, function(i) {
tryCatch({
print(i)
if (i==7) stop("Urgh, the iphone is in the blender !")
if (i==9) stop("Urgh, the iphone is in the blender !")
if (i==14) stop("Urgh, the iphone is in the blender !")
}, error=function(e){
msg <- paste("ERROR :", conditionMessage(e))
message(msg)
e
})
})
err <- which(sapply(result, inherits, "error"))
err
#[1] 7 9 14
result[[14]]$message
#[1] "Urgh, the iphone is in the blender !"