【问题标题】:Skipping over error message in R跳过 R 中的错​​误消息
【发布时间】:2016-09-27 16:53:56
【问题描述】:

我已经阅读了很多关于使用tryCatch()(来自本网站和其他网站)的信息,但我似乎无法让它发挥作用。我知道这是一个多余的问题,我很抱歉,但我真的可以使用帮助。

read.rwl() 打破了我的循环,因为我试图读取的一些数据很混乱。我想跳过来自list.rwl 的任何破坏我循环的 URL,同时将否则会破坏循环的 URL 保存为对象。

itrdb <- read.csv ("itrdb.csv")
itrdb.rwl <- (itrdb [,7])

library (dplR)

for (i in 1:length(itrdb)) {
list.rwl <- as.character (rwl.crn [1] [i])
skip_with_message = simpleError('Did not work out')
x <- tryCatch(read.rwl (list.rwl), error = function(e) skip_with_message)
}

【问题讨论】:

  • 如果您使用非基础包中的函数,您应该包含 library() 调用以获取所需的所有内容。并且您应该包含正在使用的对象的 dput。
  • 尝试重新阅读其中的一些资源。我怀疑他们是否建议您像上面那样使用tryCatch
  • 感谢 cmets 的帮助。我知道我没有远程使用 tryCatch。我尝试了其他变体无济于事,因此我发布了我的问题。

标签: r loops try-catch


【解决方案1】:

一旦您使用tryCatch 发现错误,您就可以对其进行处理。在下面的示例中,我只是捕获错误(或生成随机数),但您可以条件生成 NA 或任何可能适合您的流程的内容。有关更多示例,请参阅?tryCatch

x <- as.list(rep(NA, 10))

set.seed(357)
for (i in 1:10) {
  feelin.lucky <- runif(1)

  if (feelin.lucky >= 0.5) {
    x[[i]] <- tryCatch({
      simpleError("this is error")
    }, error = function(e) e)
  } else{
    x[[i]] <- rnorm(1)
  }
}

> x
[[1]]
[1] -1.597783

[[2]]
[1] 0.3947471

[[3]]
<simpleError: this is error>

[[4]]
<simpleError: this is error>

[[5]]
<simpleError: this is error>

[[6]]
<simpleError: this is error>

[[7]]
<simpleError: this is error>

[[8]]
<simpleError: this is error>

[[9]]
[1] -0.7539072

[[10]]
[1] -0.4690151

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-06
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    • 2013-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多