如果出现错误,如何退出循环

时间:2015-05-14 16:56:33

标签: r loops

我有一个循环,我在其中搜索矩阵中的某个值。当没有这样的值退出时,该函数将抛出错误。我想在发生错误时退出循环。我该怎么做?

我正在思考这样的事情,但不确定如何在R中执行。

>>> words = 'This is a test and I try hard to make it good'.split()
>>> from itertools import groupby
>>> [next(g) for _, g in groupby(sorted(words, key=len), len)][-3]
'is'

谢谢!

2 个答案:

答案 0 :(得分:3)

您可以使用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

答案 1 :(得分:2)

你的确可以做到:

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"