Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exit loop when there's an error

Tags:

loops

r

I have a loop in which I search for some value in a matrix. When no such value exits, the function will throw an error. I want to exit the loop when the error occurs. How do I do this?

I'm thinking something like this, but not sure how to execute in R.

for (i in 1:n){
val<-#find some value in an matrix
if (val returns error) break
}

Thanks!

like image 431
qshng Avatar asked May 14 '15 16:05

qshng


1 Answers

You can indeed do:

vec = c(1,2,3,5,6)

for(u in 1:10){
     if(!is.element(u, vec))
     {
         print(sprintf("element %s not found in vec", u)) 
         break
     }
     print(sprintf("element %s found in vec", u))
}

#[1] "element 1 found in vec"
#[1] "element 2 found in vec"
#[1] "element 3 found in vec"
#[1] "element 4 not found in vec"
like image 190
Colonel Beauvel Avatar answered Oct 04 '22 13:10

Colonel Beauvel