如何使'for循环'跳过一些显示错误的迭代?

时间:2013-07-05 08:07:33

标签: r for-loop

我在R中从(1:1700)运行for循环,但是我在每次迭代中加载不同的数据。但是我在两次迭代中遇到错误(可能是因为缺少相应的数据)。

我想知道是否有任何方法可以跳过那些我得到错误的特定迭代,至少for循环应该完成所有1700次迭代,跳过上述错误显示迭代。

我必须运行for循环,没有其他选择。

2 个答案:

答案 0 :(得分:4)

Yoy可以在你的循环中使用tryCatch。这里有一个例子,我从1循环到5,对于某些计数器值,我得到一个错误(我在这里用stop创建),我抓住它然后继续计数器的其他值。

  for( i in 1:5) ## replace 5 by 1700
     tryCatch({
        if(i %in% c(2,5)) stop(e)
        print(i)   ## imagine you read a file here, or any more complicated process
        }
    ,error = function(e) print(paste(i,'is error')))

[1] 1
[1] "2 is error"
[1] 3
[1] 4
[1] "5 is error"

答案 1 :(得分:3)

我使用try来解决此类问题。它允许循环继续通过值循环而不停止错误消息。

实施例

制作数据

set.seed(1)
dat <- vector(mode="list", 1800)
dat
tmp <- sample(1800, 900) # only some elements are filled with data
for(i in seq(tmp)){
    dat[[tmp[i]]] <- rnorm(10)
}
dat

循环没有try

#gives warning
res <- vector(mode="list", length(dat))
for(i in seq(dat)){
    res[[i]] <- log(dat[[i]]) # warning given when trying to take the log of the NULL element
}

循环try

#cycles through
res <- vector(mode="list", length(dat))
for(i in seq(dat)){
    res[[i]] <- try(log(dat[[i]]), TRUE) # cycles through
}