qshng
qshng

Reputation: 897

How to exit loop when there's an error

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!

Upvotes: 6

Views: 2959

Answers (2)

Roland
Roland

Reputation: 132989

You could use try:

m <- matrix(1:16, 4)

for (i in 1:5){
  x <- try(m[i,i], silent = TRUE)
  if (inherits(x, "try-error")) break
  print(x)
}
#[1] 1
#[1] 6
#[1] 11
#[1] 16

Upvotes: 5

Colonel Beauvel
Colonel Beauvel

Reputation: 31181

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"

Upvotes: 5

Related Questions