【问题标题】:r tryCatch how to pass object to error functionr tryCatch 如何将对象传递给错误函数
【发布时间】:2013-05-23 20:20:44
【问题描述】:
myFunc <- function(x)
{
  x <- timeSeries(x, charvec=as.Date(index(x)))
  t<-tryCatch(  doSomething(x), error=function(x) rep(0,ncol(x))
  )
  t
}

如何将 x 传递给错误函数?当我运行上述内容时,我得到:

rep(0, ncol(x)) 中的错误:'times' 参数无效

【问题讨论】:

  • 阅读错误信息:它说 ncol(x) 是 NA(或者可能是 NULL 或不太可能是 Inf)。您没有说timeSeries 属于哪个包,但我猜它不会返回具有列的对象。

标签: r try-catch


【解决方案1】:

error 参数是一个处理程序,记录在案(参见?tryCatch)以接受一个参数(错误条件)。错误处理程序可以访问在调用stop 时可用的任何变量。所以

f = function() {
    tryCatch({
        i = 1
        stop("oops")
    }, error=function(e) {
        stop(conditionMessage(e), " when 'i' was ", i)
    })
}

捕获代码抛出的错误,发现值i,并发出信息更丰富的消息。所以我猜

myFunc <- function(x)
{
    tryCatch({
        x <- timeSeries(x, charvec=as.Date(index(x)))
        doSomething(x)
    }, error=function(...) rep(0, ncol(x)))
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-01
    • 2021-11-26
    • 1970-01-01
    • 2022-12-05
    • 1970-01-01
    • 2020-05-09
    • 2012-10-28
    • 2015-11-23
    相关资源
    最近更新 更多