r tryCatch如何将对象传递给错误函数

Man*_*oon 3 r try-catch

myFunc <- function(x)
{
  x <- timeSeries(x, charvec=as.Date(index(x)))
  t<-tryCatch(  doSomething(x), error=function(x) rep(0,ncol(x))
  )
  t
}
Run Code Online (Sandbox Code Playgroud)

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

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

Mar*_*gan 5

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

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

捕获代码抛出的错误,发现值i,并发出更多信息.所以我猜

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