ManInMoon
ManInMoon

Reputation: 7005

r tryCatch how to pass object to error function

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

How do I pass x into the error function? When I run the above I get:

Error in rep(0, ncol(x)) : invalid 'times' argument

Upvotes: 4

Views: 2752

Answers (1)

Martin Morgan
Martin Morgan

Reputation: 46886

The error argument is a handler, documented (see ?tryCatch) to accept one argument (the error condition). The error handler has access to whatever variables were available at the time stop was invoked. So

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

catches the error thrown by the code, discovers the value i, and emits a more informative message. So I'd guess

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

Upvotes: 5

Related Questions