【问题标题】:tryCatch store flag and store indices where error occuredtryCatch 存储标志并存储发生错误的索引
【发布时间】:2016-10-06 13:36:09
【问题描述】:

我不太了解tryCatch 的工作原理。尤其是存储错误消息的最后一部分。 Stackoverflow 上有很多关于如何使用tryCatch 的帖子,但解决方案通常只是发布一条错误消息然后继续。我想存储发生错误的 for 循环的索引,以便以后可以轻松地返回它们。我正在考虑使用 tryCatch 进行以下操作

  flag = NULL

    for(i in 1:10) { 
      do something that can cause an error
      if (error occurs) flag=c(flag,i) and move on to the next iteration
    }

理想情况下,我希望flag 在错误期间存储索引。

【问题讨论】:

  • 如果你在做for(i:10) 那么我假设i 是一个常数。您是否尝试做for(i in 1:10) 或类似的事情?另外,你读过this answer吗?
  • @C8H10N4O2 是的,请参阅更正
  • 这就是我的工作:stackoverflow.com/q/4948361/210673

标签: r


【解决方案1】:

您可能必须使用<<- 分配给父环境,尽管这可能被认为是不好的做法。例如:

a <- as.list(1:3)
flag <- integer()
for (i in 1L:5L){
  tryCatch(
    {
      print(a[[i]])
    },
    error=function(err){
      message('On iteration ',i, ' there was an error: ',err)
      flag <<-c(flag,i)
    }
  )
}
print(flag)

返回:

[1] 1
[1] 2
[1] 3
On iteration 4 there was an error: Error in a[[i]]: subscript out of bounds

On iteration 5 there was an error: Error in a[[i]]: subscript out of bounds

> print(flag)
[1] 4 5

这有帮助吗?

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2011-01-31
  • 1970-01-01
  • 1970-01-01
  • 2018-09-14
  • 2018-01-02
  • 2018-06-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多