简体   繁体   中英

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

Let's say I have this for loop

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. As soon as a condition occurs, the loop will be stopped and control is transferred to corresponding warning or error functions.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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