[英]Save the Results From For Loop When There Is an Error R
假設我有這個for循環
results<-c()
score<-c(19,14,13,9,"A",15)
for(index in 1:length(score)){
results[index]<- index + score[index]
}
錯誤發生之前如何返回結果?
> results
[1] 20 16 16 13
我可以在循環工作時停止循環,甚至沒有完成所有索引就返回結果嗎?
您可以嘗試使用tryCatch這樣捕獲警告或錯誤。 一旦情況發生,循環將停止,控制權將轉移到相應的warning
或error
功能。
results<-c()
score<-c(19,14,13,9,"A",15)
tryCatch(expr = {
for(index in 1:length(score)){
results[index]<- index + as.numeric(score[index])
}
},warning=function(w){print(w)},
error=function(e){print(e)},
finally = results)
<simpleWarning in doTryCatch(return(expr), name, parentenv, handler): NAs introduced by coercion>
> results
#[1] 20 16 16 13
我認為這里提供了方便的中斷流控制:
results<-c()
score<-c(19,14,13,9,"A",15)
for(index in 1:length(score)){
if(is.na(suppressWarnings(as.numeric(score[index])))){
break
}
results[index]<- index + as.numeric(score[index])
}
results
#[1] 20 16 16 13
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.