Condition Handling: reusing restart functions

I have a few functions where my restarts are getting repetitive. Things like, if something fails I'd like to just return NA or NULL values. Is it possible to define restarts outside of withRestarts() and still have them findable from withCallingHandlers()

An example of what works, if I were to also define mean and median functions to handle NAs in the same way, I would have the Return_NA_Restart code multiple times.

sumVector_wRestart <- function(v){
  withCallingHandlers(
    sumVector(v),
    error = function(e) invokeRestart("Return_NA_Restart", e)
  )
}

sumVector <- function(v){
  withRestarts({
    if(any(is.na(v))) stop("Missing Value")
    sum(v)
  },
  Return_NA_Restart = function(e) return(NA)
  )
}

the closest I can get is defining a function and then calling it in an anonymous restart.

sumVector <- function(v){
  withRestarts({
    if(any(is.na(v))) stop("Missing Value")
    sum(v)
  },
  Return_NA_Restart = function(e)  Return_NA_Restart(e)
  )
}

Return_NA_Restart <- function(e){
  return(NA)
}

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.