繁体   English   中英

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

[英]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这样捕获警告或错误。 一旦情况发生,循环将停止,控制权将转移到相应的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

我认为这里提供了方便的中断流控制:

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