简体   繁体   English

当出现错误R时,从For循环保存结果

[英]Save the Results From For Loop When There Is an Error R

Let's say I have this for loop 假设我有这个for循环

results<-c()
score<-c(19,14,13,9,"A",15)
for(index in 1:length(score)){
 results[index]<- index + score[index]
}

how can I return the results before the error happen? 错误发生之前如何返回结果?

> results
[1] 20 16 16 13

Can I stop the loop while its working and return results even didn't finish all the index? 我可以在循环工作时停止循环,甚至没有完成所有索引就返回结果吗?

You can try capturing the warning or error like this using tryCatch. 您可以尝试使用tryCatch这样捕获警告或错误。 As soon as a condition occurs, the loop will be stopped and control is transferred to corresponding warning or error functions. 一旦情况发生,循环将停止,控制权将转移到相应的warningerror功能。

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

I think here comes break flow control handy: 我认为这里提供了方便的中断流控制:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM